February 2012
Intermediate to advanced
1184 pages
37h 17m
English
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" ) {
$HoA{$group} = [ get_family($group) ];
}
for $group ( "simpsons", "jetsons", "flintstones" ) {
@members = get_family($group);
$HoA{$group} = [ @members ];
}You can append new members to an existing array like so:
push @{ $HoA{flintstones} }, "wilma", "pebbles";Read now
Unlock full access