First ... Back ... Next ... Last ... (Notes home)

Types of Arrays in Perl: Hashes

Associative arrays, or hashes, are one of the great time-savers in programming with Perl.

  • Hashes or associative arrays have other types of indexes than just integers, but the real difference is in how values are stored and accessed. Rather than being accessed as a function of their index offset, they are accessed through a hash function performed on their index. Hashes are ideal for situations where there is no logical ordering for the indexes (or there is too much possible range), for when the distribution of indexes is unknown or likely to change, and for when linear-time input and output is needed.
  • Example:
    my %assoc;
    $assoc{"red"} = "FF0000";
    $assoc{"green"} = "00FF00";
    $assoc{"blue"} = "0000FF";
    print "Please see the <font color=\"" . $assoc{"red"} . "\">"red</font> text.\n";
    
  • Functions for hashes include:
    • delete: remove an entry
    • each: returns a list of
    • exists: a test for whether an entry exists
    • keys: returns a list of keys (that is, indexes)
    • values: returns a list of values
  • Example:
    my %assoc;
    while (<>) {
      if (! exists ($assoc{$_})) {
        $assoc{$_} = 1;
      } else {
        $assoc{$_} ++;
     }
    }
    
  • The main thing that is far less efficient with hashes versus regular arrays is accessing elements in a particular order. Usually this requires sorting (on either the keys or the values), which is computationally expensive.

First ... Back ... Next ... Last ... (Notes home)

UAF Computer Science
Prof. Greg Newby