February 2012
Intermediate to advanced
1184 pages
37h 17m
English
Here are some techniques for populating a hash of hashes. To read from a file with the following format:
flintstones: husband=fred pal=barney wife=wilma pet=dino
you could use either of the following two loops:
while ( <> ) {
next unless s/^(.*?):\s*//;
$who = $1;
for $field ( split ) {
($key, $value) = split /=/, $field;
$HoH{$who}{$key} = $value;
}
}
while ( <> ) {
next unless s/^(.*?):\s*//;
$who = $1;
$rec = {};
$HoH{$who} = $rec;
for $field ( split ) {
($key, $value) = split /=/, $field;
$rec–>{$key} = $value;
}
}If you have a subroutine get_family that returns a list of
key/value pairs, you can use it to stuff %HoH with either of these three
snippets:
for $group ( "simpsons", "jetsons", "flintstones" ) {
$HoH{$group} = { get_family($group) };
}
for $group ( "simpsons", "jetsons", "flintstones" ) {
@members = get_family($group);
$HoH{$group} = { @members };
}
sub hash_families {
my @ret;
for $group ( @_ ) {
push @ret, $group, { get_family($group) };
}
return @ret;
}
%HoH = hash_families( "simpsons", "jetsons", "flintstones" );You can append new members to an existing hash like so:
%new_folks = (
wife => "wilma",
pet => "dino";
);
for $what (keys %new_folks) {
$HoH{flintstones}{$what} = $new_folks{$what};
}Read now
Unlock full access