Perl Programming/Hash Variables
From Wikibooks, the open-content textbooks collection
A Perl hash is similar to an ordinary array, but instead of using integer indexes, a hash uses "keys" that can take on any scalar value. These are usually strings or numbers.
Syntax: instead of the @ operator, associative arrays use the % symbol, and rather than square brackets [], as in $myarray[0], hash elements are referenced using curly brackets {}, as in $myhash{"george"}
Hashes are one of the most powerful and commonly used features in Perl. A typical use would be to build a hash that contains a "dictionary", with each key being a word in the dictionary, and the corresponding values being the definitions of those words.
A hash containing the sounds various household pets make is below
my %petsounds = ("cat" => "meow", "dog" => "woof", "snake" => "hiss");
To access a hash element, use the curly brackets:
print STDOUT "The cat goes " . $petsounds{"cat"} . ".\n";
will print the following to STDOUT
The cat goes meow.
To add a new sound item to a hash
$petsounds{"mouse"} = "squeak!";
To overwrite an existing element, just reassign it
$petsounds{"dog"} = "arf!"; # The dog now goes "arf!"
To remove an item from a hash, use delete. Setting the value to undef does not delete the item; using exists on a key that has been set to undef will still return true.
delete($petsounds{"cat"}); # will remove "cat" from our hash
[edit] "Associative Arrays"
Originally, a "hash" was called an "associative array", but this term is a bit outdated (people just got sick and tired of using seven syllables). Although it isn't intuitive for newcomers to programming, "hash" is now the preferred term. The name is derived from the computer science term, hashtable. ,m,.
[edit] Printing Arrays
If you know PHP, you may have thought by now of some convenient way to print the contents of your array the print_r does...
use Data::Dumper; print Dumper(\%hash);
[edit] Hash of Hashes of Hashes
Indeed you may produce multidimensional hash array variable. It may look like this:
#!/usr/bin/perl use Data::Dumper; my %a=(); $a{1}{"a"}{"A"}="FIRST"; $a{1}{"c"}{"B"}="THIRD"; $a{1}{"b"}{"C"}="SECOND"; foreach my $k1 ( sort keys %a ) { foreach my $k2 ( sort keys %{$a{$k1}} ) { foreach my $k3 ( sort keys %{$a{$k1}{$k2}} ) { print "$k1\t$k2\t$k3\t$a{$k1}{$k2}{$k3}\n"; } } } print Dumper(\%a);
This code will produce:
1 a A FIRST
1 b C SECOND
1 c B THIRD
$VAR1 = {
'1' => {
'c' => {
'B' => 'THIRD'
},
'a' => {
'A' => 'FIRST'
},
'b' => {
'C' => 'SECOND'
}
}
};

