Perl - Hash Functions
In a Nutshell - CIW Course Section 2, Part B1, Chapter 8
Querying Hashes
It is likely that, at some stage, you will need to iterate through the values contained in your hash. A simple foreach statement works, after a fashion, but returns keys and values in a completely random disassociated manner.
Keys function
The keys function returns an array of all the keys in a hash and can be used in a foreach loop to return the values in a sensible orderly fashion:
%creature = ("dog" => "mammal", "snake" => "reptile", "locust" => "insect");
foreach $key (keys(%creature))
{
print ("$key\t$creature{$key}\n");
}
$key represents each key in the array returned by the keys function. The print statement then print this key and uses it to look up the associated value from the hash.
Values function
The values function is almost identical to the keys function excpet that the array returned contains the values from the hash.
%creature = ("dog" => "mammal", "snake" => "reptile", "locust" => "insect");
@genus = values(%creature);
print ("@genus\n");
Output: insect reptile mammal
Each function
The each function returns a pair of values which may be assigned to a pair of scalar variables:
($beast, $genus) = each(%creature);
Subsequent calls to each will return the next pair from the hash until all elements in the hash have been used when each returns nothing. This allows it to be used in a while loop:
%creature = ("dog" => "mammal", "snake" => "reptile", "locust" => "insect");
while (($beast, $genus) = each(%creature))
{
print ("$beast\t$genus\n");
}
Reverse function
The reverse function swaps keys and values and assigns this to new hash.
| Creature Hash | |
|---|---|
| Key | Value |
| dog | mammal |
| snake | reptile |
| locust | insect |
If we now use the reverse function: %beastie = reverse(%creature); we end up with the following:
| Beastie Hash | |
|---|---|
| Key | Value |
| mammal | dog |
| reptile | snake |
| insect | locust |
The reverse function has one major caveat, which has to do with the fact that the keys must be unique where values do not need to be. Using the above hash let's add an element containing cat/mammal as the pair. The keys are unique but the values contain "mammal" twice. If we reverse this hash it would create a non-unique key, so one of the mammal pairs must be dropped. Due to the random nature of hash storage it is impossible to predict which pair will be lost.

