Free Web Hosting by Netfirms
Web Hosting by Netfirms | Free Domain Names by Netfirms

hashes

Hashes

A hash variable stores a array of (key, value) pairs, collectively known as a map. Typically, the key and value are different but related values, such as a person's name and phone number. A hash is implemented in Perl so that you can quickly look up the value given the key, when there are many (key, value) pairs. From a algorithms/data structures standpoint, a Perl hash implements a dictionary, mostly likely using a hash table.

For example, given the name of a state, such as california, I want the Postal abbreviation, CA. We define, initialize, and modify a hash, %abbrevTable as follows.

my(%abbrevTable) = (           # this is the initialization syntax.

    "california" => "CA",      # key = california, value = CA

    "oregon" => "OR",

);

sub printAbbrev($) {

    my($state) = @_;

    if (exists $abbrevTable{$state}) {

        print "Abbreviation for $state = $abbrevTable{$state} \n";

    } else {

        print "No known abbreviation for $state\n";

    }

}

sub hashdemo () {

    printAbbrev("arizona");             # no such key

    $abbrevTable{"arizona"} = "AZ";     # add a new (key, value) pair

    printAbbrev("arizona");             # this will succeed

}

Calling the function hashdemo() gives

No known abbreviation for arizona
Abbreviation for arizona = AZ

Note that we use the exists $hash{$key} syntax to test if a key exists in the hash table. Also a hash is assymetric in that we can lookup up entries based on the key, not the value.

If treated as an normal array/list, a hash will appear as

  (keyA, valueA, keyB, valueB, keyC, valueC, ... ).

The order of the keys will appear random[Note: The key order is based on the underlying hash function being used, we are simply listing the hash table buckets.].