The hash is one of the three basic data types with in the perl language. In the simplest form, the hash is designated with the '%' sign (often used as the mod operator within C-like languages and thus a critical part of any hashimplementation) and accessed with the curly braces: '{' and '}'.

Often called an 'associative array', the hash is used to associate one data type with some value. The key point with the hash is that this does not have to be ordinal or enumerated to access. Arrays must be indexed with numbers or objects that have a clear order to them - for example '0, 1, 2, ...'. It is impossible to index an array with real numbers or strings - how many real numbers are there between '3.1' and '3.2'? Or how many strings between 'accuse' and 'ace'? There is no clean, programmatic answer for these questions and thus the hash table is the best choice for using these objects as an index into the data structure.

With an array, to have two elements '1' and '1000', there needs to be storageallocated for all 1000 elements. The equivalent hash is much smaller (often two storage units with a bit of buffer for more if necessary). In this way, the hash can be used as a sparse array for when most of the elements are '0' or empty with a very few items spread out over vast distances.

Another common use for hashes is counting elements or identifying all of the unique items - such as the following snipit demonstrates:

keys takes a hash (such as %counter) and returns a list (or array if you prefer to think that way) of the indexes to the hash. Another approach is the use of each which will iterate through the hash returning (key,value) pairs.

With perl5, the addition of references has both complicated and simplified the issues. First off, this allows for deeper data structures such as hashes of hashes and multi-dimensional arrays (which weren't supported cleanly prior to perl5). Secondly, it means that it is now much easier to pass a hash (and especially multiple hashes) to and from a subroutine. To make a reference, simply put a '\' before the name of the hash (or array, or even at times scalar). The resulting value is a scalar:

%foo = ('a' => 5, 'b' => 2);
$bar = \%foo;

Accessing a hash reference is slightly different than that of a hash, the '->' operator comes into play.

print $bar->{'a'},"\n";
5

While the '->' can be used to access individual items of the array, to use either keys or each the hash must be dereferenced. If this is a simple hash reference (like $bar above), just placing the % before it to have '%$bar' will allow the function to access the hash reference as a hash. For hashes within other data structures, is necessary to cleanly designate the entire structure:

(First the hash was set up, then the array was defined, and array element of 0 was assigned the value of the hash reference. Lastly the array element of 0 was accessed, and this scalar value dereferenced into a hash which was processed by keys and then printed.)