Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Adding to hash of hashes

by Dlamini (Novice)
on Aug 24, 2012 at 23:31 UTC ( #989657=perlquestion: print w/ replies, xml ) Need Help??
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

Comment on Adding to hash of hashes
Select or Download Code
Re: Adding to hash of hashes
by 2teez (Priest) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://989657]
Approved by GrandFather
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2015-07-05 05:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (60 votes), past polls