Associative Arrays


Beginning | Previous | Next

What is an Associative Array, or Hash?

Hashes are arrays that pair up a scalar key with a scalar value. You use the key to get the value, in other words, the key is associated with a value. Keys must be unique, but values need not be unique.

Order of Keys in a Hash

There is no "obvious" order to the keys in a hash, but are sorted to allow Perl to retrieve values quickly. They can be sorted by other operations.

Creating Hashes

There are different ways of creating associative arrays. Some examples are: # $a{0} = 'a', $a{1} = 'b', $a{2} = 'c' %a = (0, 'a', 1, 'b', 2, 'c'); # less or more readable depending on if you # started learning w/ Perl version 4 or 5 %b = (larry => fine, moe => howard); %c = (); # clear the hash

Examples of Hashes that Already Exist in Perl

Two examples are:

Accessing Elements

You access hash values, which are scalars, with the syntax: $hash{'some_key'} = $some_value; $a = $date{feb}; $address{town} = 'Beantown'; As usual, to reference a scalar, you prefix the name with a $ sign.

Getting to Keys and Values of an Associative Array

To access values of these hashes, we use the keys() function. Here is an example of how to print out all our sorted environment variables and their values: foreach $value (sort (keys (%ENV))) { print "$value = $ENV{$value}\n"; } Here foreach, similar to the csh shell, will set $value to all the possible values of the sorted keys of %ENV. We then print out the key and the associated value, $ENV{$value}.

Beginning | Previous | Next
Last Modified: $Date: 1997/05/02 07:17:39 $