B.7
Hashes
A
hash
(also called an associative array) is a collection of zero or more
pairs of scalar values, called keys and values. The values are
indexed by the keys. An array variable begins with the percent sign
% followed by a legal variable name. For instance,
possible hash variable names are:
%hash1
%genes_by_name
You can assign a value to a key with a simple assignment statement.
For example, say you have a hash called
%baseball_stadiums and a key
Phillies to which you want to assign the value
Veterans Stadium. This statement accomplishes the
assignment:
$baseball_stadiums{'Phillies'} = 'Veterans Stadium';
Note that a single hash value is referenced by a $
instead of a % at the beginning of the hash name;
this is similar to the way you reference individual array values by
using a $ instead of a @.
You can assign several keys and values to a hash by placing their
scalar values in a list, separated by commas and surrounded by a pair
of parentheses. Each successive pair of scalars becomes a key and a
value in the hash. For instance, you can assign a hash the empty
list:
%hash = ( );
You can also assign one or more scalar key-value pairs:
%genes_by_name = ('gene1', 'AACCCGGTTGGTT', 'gene2', 'CCTTTCGGAAGGTC');
There is an another way to do the same thing, which makes the
key-value pairs more readily apparent. This accomplishes the same
thing as the preceding example:
%genes_by_name = (
'gene1' => 'AACCCGGTTGGTT',
'gene2' => 'CCTTTCGGAAGGTC'
);
To get the value associated with a particular key, precede the hash
name with a $ and follow it with a pair of curly
braces { } containing the scalar value of the key:
$genes_by_name{'gene1'}
This returns the value 'AACCCGGTTGGTT', given the
value previously assigned to the key 'gene1' in
the hash %genes_by_name. Figure B-2 shows a hash with three keys.