Perl hashes are extremely useful data structures that allow us to associate one piece of data to another. In this article, Jasmine will review hashes and introduce some of their more advanced uses.
Hashes consist of one or more individual keys and its associated value. Each key and value are called pairs. There are several ways to insert these pairs into hashes, outline below.
If you know (at least some of) the key/value pairs that you would like to use, the following is the most straightforward way to assign pairs to hashes:
The above is a more readable way to assign key/value pairs. Let's not forget the importance of having easy to read code. A less readable way to assign keys and values to hashes is below:
%hash = qw(apples 6 oranges 5 pears 3 grapes 2);
Perl will automatically convert the above to key/value pairs as if you used the arrows => in the first example. We recommend the first format's example for readability, though the formats can be used interchangeably.
You can also add each key/value pair individually. The following line adds a new key/value pair to our original hash.
$hash
{peach} = 3;
If the original hash did not exist, this line would have created a new hash and inserted the first key/value pair as defined. The process by which a variable can spring into life like this is called autovivification.
This is useful if you need to loop through a data file and would like to insert data from the file to a hash.
open FILE
, "fruits.txt" or die $!; while (){ chomp; my @line = split(/ /); $hash{$line[0]} = $line[1]; } close FILE or die $!;
Removing Pairs from Hashes Now that we know how to add pairs to hashes, we need to know how to get rid of them. Deleting a pair is as easy as knowing the key of the pair you want deleted:
delete $hash
{peach};
Now, the pair whose key is peach is gone. But what if you wanted to delete the entire hash? You can either loop through the entire hash and delete each key (inefficient) or you can undef it:
undef
%hash;
Do not use:
%hash = undef;
This will not obliterate the hash, it will assign a single key/value pair of undef/undef. If you want to remove all keys from the hash, but still keep %hash as an "active" variable, use:
%hash = ();
Looking inside Hashes We now know how to add and remove pairs from hashes, but how to see what pairs are there? As with nearly everything Perl, TIMTOWTDI (there is more than one way to do it). Here, we'll look at a few examples on how to loop inside hashes and take a peek at what's inside. These examples assume you're already familiar with loops.