Hashes of Hashes
A multidimensional hash is the most flexible of Perl's
nested structures. It's like building up a record that itself contains
other records. At each level, you index into the hash with a string
(quoted when necessary). Remember, however, that the key/value pairs
in the hash won't come out in any particular order; you can use the
sort function to retrieve the pairs in whatever
order you like.
Composition of a Hash of Hashes
You can create a hash of anonymous hashes as follows:
%HoH = (
flintstones => {
husband => "fred",
pal => "barney",
},
jetsons => {
husband => "george",
wife => "jane",
"his boy" => "elroy", # Key quotes needed.
},
simpsons => {
husband => "homer",
wife => "marge",
kid => "bart",
},
);To add another anonymous hash to
%HoH, you can simply say:
$HoH{ mash } = {
captain => "pierce",
major => "burns",
corporal => "radar",
};Generation of a Hash of Hashes
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access