Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Merge Hashrefs

by oakbox (Chaplain)
on Jan 10, 2005 at 12:19 UTC ( #420887=perlquestion: print w/replies, xml ) Need Help??

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

I've got 2 (or more) hashrefs that I would like to combine. I'm wondering if there is a simpler method of merging them than the brute force way I'm using:
my $object; my $subobject; foreach my $keyn (keys %{$subobject}){ $object->{$keyn} = $subobject->{$keyn}; }
In real life, these hashreferences would each have between 50 and 150 elements. The above code isn't a huge drain, but it seems inelegant. Is there a handy methodology that I'm missing here?

Replies are listed 'Best First'.
Re: Merge Hashrefs
by Thilosophy (Curate) on Jan 10, 2005 at 12:36 UTC
      But this goes only one level deep. For "deeper" hash structures (like $object->{level1}{level2}=$value) this fails. See example:
      use strict; use Data::Dumper; my $x = { a => 1, b => 2, aa => { aaa => 11 } }; print Dumper($x); my $y = { c => 3, d => 4, aa => { bbb => 11 } }; print Dumper($y); $x = { %$x, %$y }; print Dumper($x);
      Gives (see below) with "aaa" key in 'aa'=>'aaa'=>22 lost
      $VAR1 = { 'c' => 3, 'a' => 1, 'b' => 2, 'd' => 4, 'aa' => { 'bbb' => 11 } };
      UPDATE: check this thread how to do it using Hash-Merge In a nut shell, add as appropriate:
      use Hash-Dumper qw/merge/;
      and modify
      $x = { %$x, %$y };
      $x = merge( $x, $y );
      and resulting hash will look much better
      $VAR1 = { 'c' => 3, 'a' => 1, 'b' => 2, 'd' => 4, 'aa' => { 'bbb' => 11, 'aaa' => 11 } };
        > But this goes only one level deep.

        Of course!

        Since there are many possible interpretations of what a "deep merge" should do, you should script it in a recursive way after your well defined needs.

        Cheers Rolf

        (addicted to the Perl Programming Language and ☆☆☆☆ :)


        see also how to merge hash deeply ?

        ) for example what do you expect to happen if both hashes have the same scalar entry?

        %a = (x=>1}; %b = (x=>2);
      Well I guess that is simple enough!

      Thank you

        Note that the above is *really* inefficient (or at least it was). You might consider:  @hash1{ keys %hash2 } = values %hash2; Which is more efficient.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (7)
As of 2020-03-31 02:50 GMT
Find Nodes?
    Voting Booth?
    To "Disagree to disagree" means to:

    Results (179 votes). Check out past polls.