As a relatively new user of Perl's hash of hashes I still find some things hard to figure out.
I have a database I am doing in perl where it is difficult to predict all the variables that might apply to a individual kind of data field and I have recently discovered that a technique used in library book cataloging where a kind of datafield may have several sub data fields can be implemented using hash of hashes and hash of arrays, etc.
For example and individual's record might have an unpredictable number of awards earned. So the awards field can be a hash with award type for the key and award date for the value.
So then I came to a point where I wanted to extract an individual's record (which is itself a hash) from the main database hash of records and assign it to a hash for sending to a subroutine for processing . Lots of searching with google failed to give me a result on "extract hash from hash of hashes and assign it to its own hash" or variations on this theme.
So I finally found the article at perldoc on hashes and hashes of hashes and used it to figure out how to retrieve an individual record as a hash. But I would like to post the solution so other people might be able to find out how it is done directly:
Original code inspiring this:
perldsc#!/usr/bin.perl #hashes of hashes test.pl %HoH = ( flintstones => { lead => "fred", pal => "barney", }, jetsons => { lead => "george", wife => "jane", "his boy" => "elroy", }, simpsons => { lead => "homer", wife => "marge", kid => "bart", }, ); #endhoh # print the whole thing foreach $family ( keys %HoH ) { print "$family: { "; for $role ( keys %{ $HoH{$family} } ) { print "$role=$HoH{$family}{$role} "; } print "}\n"; } #print one family (which is a hash) and assign it to a hash print " print family simpsons\n"; $family ='simpsons'; for $role ( keys %{ $HoH{$family} } ) { print "\t$role=$HoH{$family}{$role} "; $simpsons{$role}=$HoH{$family}{$role}; #this works } print "}\n"; print "lead simpsons is: $simpsons{lead}\n"; #assign the families to a hash %newsimpsons = %{ $HoH{$family} }; #this works but you must provide a +value for $family %jetsons = %{ $HoH{'jetsons'} }; #this works but you must provide a va +lue in $HOH{'value'} "which can be a string print "lead simpsons is: $newsimpsons{lead}, lead jetsons is $jetsons{ +lead}\n";
In reply to RFC How to retrieve a hash from a hash of hashes by bdalzell
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |