Perl: Hash Table

By Xah Lee. Date: . Last updated: .

A hash table is a unordered collection of key and value pairs.

Create a Hash Table

use Data::Dumper qw(Dumper);  # load the Dumper function for printing array/hash

$Data::Dumper::Indent = 0;  # make it print in compact style

# hash table
%hh = ('john'=>3, 'mary'=> 4, 'joe'=> 5, 'vicky'=>7);

print Dumper \%hh;   # {'joe' => 5,'john' => 3,'vicky' => 7,'mary' => 4}

Variable of hash datatype must begin with % in their name.

If you are going to get values of a hash, you use $ in front of the hash variable. e.g. $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)

Add/Modify a Entry

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

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

$hh{'c'} = 5;

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

Delete a Entry

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};

Check If Key Exist

%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)

Get Key's Value

use Data::Dumper qw(Dumper);

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

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

Get All Keys

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

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]

Perl, data structure