Perl: Hash Table (Key/Value List)

, , …,

In Perl, keyed-list is called hash table, or just hash. It is done like this:

Creating a hash table.

# -*- coding: utf-8 -*-
# perl

use Data::Dumper qw(Dumper); # load Data::Dumper, for printing array/hash
$Data::Dumper::Indent = 0;   # make it print in compact style

# create a hash table
%hh = ('a' =>3, 'b' => 4, 'c' => 5);
print Dumper \%hh;              # {'c' => 5,'a' => 3,'b' => 4};

Get value of a key:

# -*- coding: utf-8 -*-
# perl

use Data::Dumper qw(Dumper);

%hh = ('john' =>3, 'mary' => 4, 'jane' => 5);

# get value of a key
print $hh{'mary'};              # 4

Delete a entry:

# -*- coding: utf-8 -*-
# perl

use Data::Dumper qw(Dumper);
$Data::Dumper::Indent = 0;

%hh = ('a' =>3, 'b' => 4, 'c' => 5);

# delete a entry
delete $hh{'b'};

print Dumper \%hh;         # {'c' => 5,'a' => 3};

Get all keys:

# -*- coding: utf-8 -*-
# perl

use Data::Dumper qw(Dumper);
$Data::Dumper::Indent = 0;

%hh = ('a' =>3, 'b' => 4, 'c' => 5);

# get all keys
print Dumper [keys %hh];        # ['c','a','b']

Get all values:

# -*- coding: utf-8 -*-
# perl

use Data::Dumper qw(Dumper);
$Data::Dumper::Indent = 0;

%hh = ('a' =>3, 'b' => 4, 'c' => 5);

# get all values
print Dumper [values %hh];      # [5,3,4]

Check if a key exist:

# -*- coding: utf-8 -*-
# perl

use Data::Dumper qw(Dumper);
$Data::Dumper::Indent = 0;

%hh = ('a' =>3, 'b' => 4, 'c' => 5);

# check if a key exists
print exists $hh{'b'};          # 1
print exists $hh{'d'};          # (doesn't print anything)

If you are going to get values of a hash, you use $ in front of the hash variable. ⁖ $‹hash›{'‹name›'}.

The Dumper function's argument needs to be a “reference” to the hash. So, you can use it like this: Dumper(\%‹hash›) or Dumper([%‹hash›]). (parenthesis is usually optional)

blog comments powered by Disqus