Access and Printing of a Hash of Hashes
You can set a key/value pair of a particular hash as follows:
$HoH{flintstones}{wife} = "wilma";To capitalize a particular key/value pair, apply a substitution to an element:
$HoH{jetsons}{"his boy"} =~ s/(\w)/\u$1/;You can print all the families by looping through the keys of the outer hash and then looping through the keys of the inner hash:
for $family ( keys %HoH ) {
print "$family: ";
for $role ( keys %{ $HoH{$family} } ) {
print "$role=$HoH{$family}{$role} ";
}
print "\n";
}In very large hashes, it may be slightly faster to retrieve
both keys and values at the same time using each (which precludes sorting):
while ( ($family, $roles) = each %HoH ) {
print "$family: ";
while ( ($role, $person) = each %$roles ) {
print "$role=$person ";
}
print "\n";
}(Unfortunately, it’s the large hashes that really need to be sorted, or you’ll never find what you’re looking for in the printout.) You can sort the families and then the roles as follows:
for $family ( sort keys %HoH ) {
print "$family: ";
for $role ( sort keys %{ $HoH{$family} } ) {
print "$role=$HoH{$family}{$role} ";
}
print "\n";
}To sort the families by the number of members (instead of
ASCIIbetically [or utf8ically]), you can use keys in scalar context:
for $family ( sort { keys %{$HoH{$a}} <=> keys %{$HoH{$b}} } keys %HoH ) {
print "$family: ";
for $role ( sort keys %{ $HoH{$family} } ) {
print "$role=$HoH{$family}{$role} ";
}
print "\n";
}To sort the members of a family in some fixed order, ...
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