Concepts of Programming Languages

(Sean Pound) #1
6.6 Associative Arrays 273

a value, which is a scalar (number, string, or reference). Hashes can be set to
literal values with the assignment statement, as in

%salaries = ("Gary" => 75000, "Perry" => 57000,
"Mary" => 55750, "Cedric" => 47850);

Individual element values are referenced using notation that is similar to
that used for Perl arrays. The key value is placed in braces and the hash name is
replaced by a scalar variable name that is the same except for the first character.
Although hashes are not scalars, the value parts of hash elements are scalars, so
references to hash element values use scalar names. Recall that scalar variable
names begin with dollar signs ($). For example,

$salaries{"Perry"} = 58850;

A new element is added using the same assignment statement form. An element
can be removed from the hash with the delete operator, as in

delete $salaries{"Gary"};

The entire hash can be emptied by assigning the empty literal to it, as in

@salaries = ();

The size of a Perl hash is dynamic: It grows when an element is added and
shrinks when an element is deleted, and also when it is emptied by assignment
of the empty literal. The exists operator returns true or false, depending on
whether its operand key is an element in the hash. For example,

if (exists $salaries{"Shelly"})...

The keys operator, when applied to a hash, returns an array of the keys of
the hash. The values operator does the same for the values of the hash. The
each operator iterates over the element pairs of a hash.
Python’s associative arrays, which are called dictionaries, are similar
to those of Perl, except the values are all references to objects. The associa-
tive arrays supported by Ruby are similar to those of Python, except that
the keys can be any object,^6 rather than just strings. There is a progression
from Perl’s hashes, in which the keys must be strings, to PHP’s arrays, in
which the keys can be integers or strings, to Ruby’s hashes, in which any
type object can be a key.
PHP’s arrays are both normal arrays and associative arrays. They can be
treated as either. The language provides functions that allow both indexed and


  1. Objects that change do not make good keys, because the changes could change the hash
    function value. Therefore, arrays and hashes are never used as keys.

Free download pdf