bdalzell has asked for the wisdom of the Perl Monks concerning the following question:
Recently I returned to working on a complex program that uses a hash of hashes (H0H) as a database.
There is a section that creates a new child hash that then has to be added to the large HoH.
I had forgotten how to add an already created child hash to a hash of hashes.
Trying to Google things did not help. All the answers had you create the child hash while adding it to the HoH.
My large application needs to have a keyname which is also stored in the child hash as part of the information with in the child hash.
I am not trying to start a discussion about what is in the hash or the need for the keyname.
Here are two ways to add a preexisting child hash to the HoH:
Add the child hash directly:
$HoH{"$key"} = ({%child_hash);add by reference to new child hash
$HoH{"$key"} = \%child_hash;Here is a working sample script which contains comments
#!/usr/bin/perl my %HoH= ( 'test1' => { 'keyname'=>'test1', 'price' => '10.00', 'desc' => 'the +1st test'}, 'test2' => { 'keyname'=>'test2', 'price' => '12.00', 'desc' => 'the +2nd test'}, 'test3' => { 'keyname'=>'test3', 'price' => '13.00', 'desc' => 'the +3rd test'}, 'test4' => { 'keyname'=>'test4', 'price' => '14.00', 'desc' => 'the +4th test'} ); my %child_hash = &new_hash; my $key = $child_hash{'keyname'}; ## 2 ways to add a newly made hash to the hash of hashes # directly # $HoH{"$key"} = ({%child_hash}); # or by reference $HoH{"$key"} = \%child_hash; my @keys = keys %file_tests; @keys = sort @keys; foreach my $key(@keys){ print "$key price is: $HoH{$key}{'price'}\n"; } sub new_hash { my %hash = ( 'keyname' => 'test5', 'price' => "20.00", 'desc' => "the 5th test"); return %hash; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Add child hash to hash of hashes.
by haukex (Archbishop) on May 29, 2017 at 18:10 UTC | |
|
Re: Add child hash to hash of hashes.
by bdalzell (Sexton) on May 29, 2017 at 17:28 UTC |