Hashes in Perl

Hash is an associative array

o A data structure with key – value, where the key is a unique string

o Perl processes big hashes just as fast as small ones. Hashes are most useful when dealing with

  • Finding duplicates
  • Unique
  • Cross reference
  • Lookup table
  • Hash expression:
$hash{$key} = $value;
 $hash{$key} .= $hash{$key2}; #creates key element appended from key2 value
 $value2 = $hash{$dne_key}; #if key doesn’t exist, value2 = undef
  • Hash as a whole

o The actual syntax for hash variable uses the “%”

o Hashes can be re-assigned to list and vice-versa

o Hash can be unwinded by turning from hash to list. This can change the list order.

%hash = ("a", 1, "b", 2, "c", 3, "d", 4, "e", 5);
 @myarray = %myhash; # unwinding the hash
 print "@myarray \n"; # e 5 c 3 a 1 b 2 d 4
  • The Big Arrow aka Fat Comma, =>

o An easier way to read the definition of a hash is by using the Big Arrow

%hash2 = (

"f" => 6,

"g" => 7,

"h" => 8,

"i" => 9,

"j" => 10

);
  • Hash Functions

o Examples of hash functions:

  • Key – the keys in the hash
  • Value – the values in the has
  • Reverse – swaps keys with values
  • Each – returns a key-value pair as two element list
  • Exists – function which returns true if value of given key exists
%hash = reverse %hash;

@keys = keys %hash;

@values = values %hash;

print "@keys \n@values \n"; # keys and values swapped, values are keys now

while(($key,$value) = each %hash){ # each function

print "$key => $value \n";

}