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.
You can create a hash of anonymous arrays as follows:
To add another array to the hash, you can simply say:# We customarily omit quotes when the keys are identifiers. %HoA = ( flintstones => [ "fred", "barney" ], jetsons => [ "george", "jane", "elroy" ], simpsons => [ "homer", "marge", "bart" ], );
$HoA{teletubbies} = [ "tinky winky", "dipsy", "laa-laa", "po" ];
Here are some techniques for populating a hash of arrays. To read from a file with the following format:
you could use either of the following two loops:flintstones: fred barney wilma dino jetsons: george jane elroy simpsons: homer marge bart
If you have a subroutine get_family that returns an array, you can use it to stuff %HoA with either of these two loops:while ( <> ) { next unless s/^(.*?):\s*//; $HoA{$1} = [ split ]; } while ( $line = <> ) { ($who, $rest) = split /:\s*/, $line, 2; @fields = split ' ', $rest; $HoA{$who} = [ @fields ]; }
You can append new members to an existing array like so:for $group ( "simpsons", "jetsons", "flintstones" ) { $HoA{$group} = [ get_family($group) ]; } for $group ( "simpsons", "jetsons", "flintstones" ) { @members = get_family($group); $HoA{$group} = [ @members ]; }
push @{ $HoA{flintstones} }, "wilma", "pebbles";
You can set the first element of a particular array as follows:
To capitalize the second Simpson, apply a substitution to the appropriate array element:$HoA{flintstones}[0] = "Fred";
You can print all of the families by looping through the keys of the hash:$HoA{simpsons}[1] =~ s/(\w)/\u$1/;
With a little extra effort, you can add array indices as well:for $family ( keys %HoA ) { print "$family: @{ $HoA{$family} }\n"; }
Or sort the arrays by how many elements they have:for $family ( keys %HoA ) { print "$family: "; for $i ( 0 .. $#{ $HoA{$family} } ) { print " $i = $HoA{$family}[$i]"; } print "\n"; }
Or even sort the arrays by the number of elements and then order the elements ASCIIbetically (or to be precise, utf8ically):for $family ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA ) { print "$family: @{ $HoA{$family} }\n" }
# Print the whole thing sorted by number of members and name. for $family ( sort { @{$HoA{$b}} <=> @{$HoA{$a}} } keys %HoA ) { print "$family: ", join(", ", sort @{ $HoA{$family} }), "\n"; }
Copyright © 2002 O'Reilly & Associates. All rights reserved.