next up previous contents index
Next: Random values Up: Variables Previous: Arrays   Contents   Index


Hashes

Accessing array elements by an integer index is at times natural (for example, in the case of a collection of test scores), but at other times, it is less intuitive. For example, suppose we have some data on a person - their name, age, and address - and want to represent that by some variable. We could use an array, with the array element with index ``0'' being the name, ``1'' the age, and ``2'' the address, but this is hard to remember, and easy to mix up. In such cases the use of a hash would be more intutive.

A hash, represented by %hash_name, can be thought of as an array where the array indices are specified not necessarily as integers but by some user-specified values. Individual elements of the hash are then accessed through the $hash_name{$key} syntax, where $key is a particular key of the hash. For example,

  %person = ('name', 'George', 'age', 33, 'address', '123 Main');
  print $person{name};
will print out ``George''. For large hashes it is sometimes hard to keep track of what are the corresponding key/value pairs - to help with this, you can use the following syntax:
 %person = ( name    => 'George',
             age     => 33,
             address => '123 Main',
           );
Note that, with this syntax, keys which are words are automatically quoted.

A few things are worth noting about hashes:


next up previous contents index
Next: Random values Up: Variables Previous: Arrays   Contents   Index