http://www.perlmonks.org?node_id=989657

Dlamini has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks

Is there an idiomatic way to add key/value pairs to a hash of anonymous hashes? For example, if I already have:

my %hoh; $hoh{element1} = {start => 1, middle => 5};

but then I want to add an  end => 10 to the same anonymous hash without replacing what's already there. I guess the problem is that the hash, being anonymous, doesn't have a name through which I can access it (other than with  keys  %hoh -- or does it?). So I can extract the anonymous hash to the top level, add to it, then replace what used to be there like so:

my %temphash = %{$hoh{element1}}; $temphash{end} = 10; $hoh{element1} = \%temphash;
but I was wondering if there is a better, more standard, idiomatic way to do this?

Thanks in advance...

Dlamini

Replies are listed 'Best First'.
Re: Adding to hash of hashes
by 2teez (Vicar) on Aug 24, 2012 at 23:56 UTC

    but then I want to add an end => 10 to the same anonymous hash without replacing what's already there

    use warnings; use strict; use Data::Dumper; my %hoh; $hoh{element1} = {start => 1, middle => 5}; print Dumper \%hoh; $hoh{element1}{end}=10; # add to hash print Dumper \%hoh;
    OUTPUT:
    $VAR1 = { 'element1' => { 'middle' => 5, 'end' => 10, 'start' => 1 } };
    For more information, please check the following: perldsc, perlref, perllol, perldata, perlobj

      Thanks, 2teez, that's exactly what I was looking for - I think I tried something similar but must have got the syntax wrong somewhere

Re: Adding to hash of hashes
by Anonymous Monk on Aug 25, 2012 at 00:15 UTC
    Or, maybe:
    use warnings; use strict; use Data::Dumper; my %hoh; $hoh{element1} = { start => 1, middle => 5 }; my @append = ( { test => 1, key => 3 }, { abc => 2, xyz => 5 } ); @{$hoh{element1}}{map keys %{$_}, @append} = map values %{$_}, @append +; print Dumper \%hoh;
Re: Adding to hash of hashes
by Anonymous Monk on Aug 25, 2012 at 07:12 UTC