Lesson 16: Hash Functions


Common hash functions

function description
keys %hash retrieve list of keys/indices from a hash
exists $hash{'key'} test whether a hash key is present
delete $hash{'key'} deletes a key/value pair from a hash
values %hash return a list of the values in a hash
each %hash retrieve the next key/value pair from a hash

keys

  • Returns a list of keys from a hash. Remember keys are like array indices.
1
2
3
4
5
6
my %jacks = ('Jack Sparrow'    => 'pirate' ,
             'Jack Black'      => 'actor',
             'Jack the Ripper' => 'murderer',
           );
my @keys = keys %jacks;
print join ('--', @keys) , "\n";

Output:

%% ./hash_functions.pl
Jack Black--Jack the Ripper--Jack Sparrow

exists

  • Returns true if the key is found in the hash.
1
2
3
4
5
if (exists $jacks{'Jack the Ripper'}){
  print "Yes, this key is present\n";
}else {
  print "No, this key is not present\n";
}

Output:

%% ./hash_functions.pl
Yes, this key is present

delete

  • Removes the provided key/value pair from the hash
1
2
3
4
5
print "before delete\n";
print Dumper \%jacks;
delete $jacks{'Jack Sparrow'};
print "after delete\n";
print Dumper \%jacks;

Output:

%% ./hash_functions.pl
before delete
$VAR1 = {
          'Jack Black' => 'actor',
          'Jack the Ripper' => 'murderer',
          'Jack Sparrow' => 'pirate'
        };
after delete
$VAR1 = {
          'Jack Black' => 'actor',
          'Jack the Ripper' => 'murderer'
        };

keys and foreach: iterating through a hash

  • using the keys function in conjunction with a foreach loop is an ideal way to iterate through each key/value pair in a hash.
1
2
3
4
foreach my $jack (keys %jacks){
  my $occupation = $jacks{$jack};
  print "This Jack: $jack is a $occupation\n";
}

Output:

%% ./hash_functions.pl
This Jack: Jack Black is a actor
This Jack: Jack the Ripper is a murderer

Exercises

  1. Create a hash, and print each key/value pair using the function keys() with a foreach loop.

Print Friendly

Leave a Reply

Your email address will not be published. Required fields are marked *