Perl Hashes
A hash in Perl is a special type of variable that stores data in key and value pairs. Unlike an array, where items are accessible using their numeric index value, items in a hash are accessible via their key, which can be of any data type.
Below is an example of a hash, called ‘people’, where the key is a string, that holds a person’s name, and the value is an integer for their age. It should be noted that when a hash is defined, the name is preceded by a '%' sign, rather than '$'.
my %people = ("Bob Smith" => 30,
"George Jones" => 21,
"Fred Bloggs" => 43,
"Alan White" => 29);
The key can be used to access its value. This will display '43' in the terminal.
print "$people{'Fred Bloggs'}";
As with arrays, it is possible to loop through a hash using a ‘foreach’ loop.
my @names = keys %people; foreach my $name (@names) { print "$name is $people{$name} years old.\n"; }
Here, the keys are copied into an array called '@names', which is then used in the ‘foreach’ loop to extract each value from the hash to display as part of a string in the terminal.
Bob Smith is 30 years old. Fred Bloggs is 43 years old. George Jones is 21 years old. Alan White is 29 years old.
It should be noted that the key and value pairs within a hash aren't necessarily stored in the same order that they are added to it.
The process for adding and editing a key and value pair is the same. If you specify a key that already exists in the hash, then its value gets updated. If you specify a key that doesn't already exist, then a new key and value pair gets added to the hash.
$people{"George Jones"} = 22;
$people{"John Smith"} = 52;
In the case of the above, the first line will update the value for the existing key, whereas, with the second line a new key and value pair will be added.
Finally, if it is necessary to remove a key and value pair from the hash, this can be achieved by using the 'delete' function. To mitigate any potential errors, the 'exists' function can be used to check for the existence of the key, before its deletion is attempted.
if (exists($people{"Fred Bloggs"})) { delete $people{"Fred Bloggs"}; print "The key and its value have been deleted.\n" } else { print "The key does not exist in the hash.\n"; }