Monday, December 05, 2005
Perl: Associative Arrays (Hashes)
You're wasting perl if you don't use associative arrays. Associative
arrays, sometimes called "hashes", are arrays that are indexed not on
ordered integers, but on arbitrary string values. Typically, elements of
an associative array are refered to as "key" and "value" pairs - the "key"
is used to find the element of the array that has the "value". Basic
operators are:
% (percent sign)
Refers to the entire array
{ } (braces)
Used to denote the key
$
When used with { }, this is the value of the array element indexed on the
key.
$principal{"clarinet"} = "Susan Bartlett";
$principal{"basson"} = "Andrew Vandesteeg";
$principal{"flute"} = "Heidi Lawson";
$principal{"oboe"} = "Jeanine Hassel";
@woodwinds = keys(%principal);
@woodwindPrincipals = values(%principal);
Some Associative Array functions
keys(%ARRAY) Return a list of all the keys in %ARRAY. The list is
"unordered" - it depends on the hash function used internally.
values(%ARRAY) Return a list of all the values in %ARRAY
each(%ARRAY) Each time this is called on an %ARRAY, it will return a 2
element list consisting of the next key/value pair in the array.
delete($ARRAY{KEY}) remove the pair associated with KEY from ARRAY.