|
|
i have a hash of hashes and i would like to get one of these subhashes into a single hash.
how do i do that?
|
|
|
|
Hi,
The below mentioned script will help you in analyzing and understanding hash of hashes operations.
#!/usr/bin/perl -w
%HoH = (
flintstones => {
husband => "fred",
pal => "barney",
},
jetsons => {
husband => "george",
wife => "jane",
"his boy" => "elroy", # Key quotes needed.
},
simpsons => {
husband => "homer",
wife => "marge",
kid => "bart",
},
);
#You can set a key/value pair of a particular hash as follows:
$HoH{flintstones}{wife} = "wilma";
#Access and Printing of a Hash of Hashes
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";
}
#To sort the families by the number of members (instead of #ASCIIbetically (or utf8ically)), you can use keys in a 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";
}
|
|
|
|
|
|
|
// |