Hashes of Arrays

Use a hash of arrays when you want to look up each array by a particular string rather than merely by an index number. In our example of television characters, instead of looking up the list of names by the zeroth show, the first show, and so on, we'll set it up so we can look up the cast list given the name of the show.

Because our outer data structure is a hash, we can't order the contents, but we can use the sort function to specify a particular output order.

Composition of a Hash of Arrays

You can create a hash of anonymous arrays as follows:

# We customarily omit quotes when the keys are identifiers.
%HoA = (
    flintstones    => [ "fred", "barney" ],
    jetsons        => [ "george", "jane", "elroy" ],
    simpsons       => [ "homer", "marge", "bart" ],
);

To add another array to the hash, you can simply say:

$HoA{teletubbies} = [ "tinky winky", "dipsy", "laa-laa", "po" ];

Generation of a Hash of Arrays

Here are some techniques for populating a hash of arrays. To read from a file with the following format:

flintstones: fred barney wilma dino
jetsons:     george jane elroy
simpsons:    homer marge bart

you could use either of the following two loops:

while ( <> ) {
    next unless s/^(.*?):\s*//;
    $HoA{$1} = [ split ];
}

while ( $line = <> ) {
    ($who, $rest) = split /:\s*/, $line, 2;
    @fields = split ' ', $rest;
    $HoA{$who} = [ @fields ];
}

If you have a subroutine get_family that returns an array, you can use it to stuff %HoA with either of these two loops:

for $group ( "simpsons", "jetsons", "flintstones" ...

Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.