Perl

03. Hashes


Hashes

Short for hash table, used to be called "associative array".

Like an array that is indexed by any scalar value (most typically strings).

No order to elements added, internal hash function arranges them as it pleases.

Can be used to simulate struct/record or relationships between data.


Syntax

Hash variables denoted by "%" prefix, use $ for a single element.

Scalar used to index the hash is referred to as the "key".

$greg{"age"} = 29;            # use as a record
$greg{"father"} = "carl";     # greg's father is carl

$greg{"age"}++;               # now 30

%a = %b;                      # copy entire hash

Trying to pull a value for a key that doesn't exist results in undef being returned.


Funny Initialization

Different ways to initialize/extract values.

=> is a form of comma, used for readability in hash assignments, forces quoting of lefthand side.

@list = ("age", 29, "father", "carl");
%greg = @list;           # use array as list of key/value pairs to init

@list = %greg;           # extract all key/value pairs into array
                         # order not predictable, may be:
                         # ("age", 29, "father", "carl") or other way around

%race = (
   winner => 'Gordon',   # initialize as pairs, really just an array,
   time => '2 hours',    #   but more readable
   prize => '$100',      # extra comma ok, can add more later
);

($hash{"a"}, $hash{"b"}) = (8, 9);
$hash{"a", "b"} = (8, 9);           # equivelant

Hash Functions

keys(%hash) will return a list of all keys to the hash (in whatever order they are in internally).

values(%hash) will return a list of all values in the hash. Both keys and values useful with loops.

each(%hash) will return "next" key/value pair. Used to walk through all pairs in random order with a loop.

delete $hash{key} will delete a key/value pair from hash.


ENV

Environment variables (provided by your shell) are available to your script in the ENV hash.

$home = $ENV{HOME};                # where is HOME?
$path = $ENV{PATH};                # what is my path?

$ENV{PATH} = "/bin:/usr/bin";      # narrow path for future use

Three Basic Types

Three basic types of data in Perl: scalar, array and hash.

Those three can be used to contruct surprisingly large set of data structures and algorithms.