CIW Course Revision Site


Perl - Introduction to Hashes

In a Nutshell - CIW Course Section 2, Part B1, Chapter 7

Hashes Overview

A hash is a special type of array, known as an associative array. Where each element in an array has a numeric index, a hash has a key. Hashes are unordered so cannot have element identified by a numeric index, and the order in which they are stores cannot be predicted.

A hash name is prefixed with the "%" symbol and contains key/value pairs. There are two ways of defining a hash:

%method1 = ("dog", "mammal", "snake", "reptile", "locust", "insect");
%method2 = ("dog" => "mammal", "snake" => "reptile", "locust" => "insect");

Both methods achieve the same result, but the second makes the key/value association more obvious.

Perhaps the best way to think of a hash, is as a table:

A Hash Table
Key Value
dog mammal
snake reptile
locust insect

When you wish to look up a value, you look down the left column for the specified item and then read the value from the adjacent cell in the right column.

Accessing Hash Elements

The values contained within a hash are accessed by their associated keys.

%creature = ("dog" => "mammal", "snake" => "reptile", "locust" => "insect");
print("$creature{snake}\n");

The keys and values in the hash are scalar values so are identified with the "$" symbol. The key is delimited with "{ }" symbols. The output from the above is example will be the word "reptile".

Deleting Hash Elements

Key/Value pairs can be deleted from a hash by specifying the key in the same way we did in the print example above:

delete($creature{snake});

The exists function can be used to determine if an element is present before use.

if (exists($creature{snake})
{
  delete($creature{snake});
}

Design by Stephen

Certified Internet Webmaster

Page last Edited: 10 Nov 2011