Perl: Hash Table
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 %xx = ('john'=>3, 'mary'=> 4, 'joe'=> 5, 'vicky'=>7); print Dumper \%xx; # {'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 Entry, Modify Entry
use Data::Dumper qw(Dumper); $Data::Dumper::Indent = 0; %xx = ('a' =>3, 'b' => 4 ); $xx{'c'} = 5; print Dumper \%xx; # $VAR1 = {'c' => 5,'a' => 3,'b' => 4};
Delete a Entry
use Data::Dumper qw(Dumper); $Data::Dumper::Indent = 0; %xx = ('a' =>3, 'b' => 4, 'c' => 5); # delete a entry delete $xx{'b'}; print Dumper \%xx; # {'c' => 5,'a' => 3};
Check If Key Exist
%xx = ('a' =>3, 'b' => 4, 'c' => 5); # check if a key exists print exists $xx{'b'}; # 1 print exists $xx{'d'}; # (doesn't print anything)
Get Key's Value
use Data::Dumper qw(Dumper); %xx = ('john' =>3, 'mary' => 4, 'joe' => 5); # get value of a key print $xx{'mary'}; # 4
Get All Keys
use Data::Dumper qw(Dumper); $Data::Dumper::Indent = 0; %xx = ('a' =>3, 'b' => 4, 'c' => 5); # get all keys print Dumper [keys %xx]; # ['c','a','b']
Get All Values
use Data::Dumper qw(Dumper); $Data::Dumper::Indent = 0; %xx = ('a' =>3, 'b' => 4, 'c' => 5); # get all values print Dumper [values %xx]; # [5,3,4]