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; }

In reply to Add child hash to hash of hashes. by bdalzell

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.