1

I am trying to merge these hashmaps in perl and unable to figure out how to do it when the key is identical. The desired input is VAR1 and VAR2 and output is mentioned as well.

Input:

my $VAR1 = { 'p'=> { 'a' => 2,
                     'b' => 3}};


my $VAR2 = { 'p'=> { 'c' => 4,
                     'd' => 7}};

Desired Output:

{'p'=> { 
        'a' => 2,
        'b' => 3,
        'c' => 4,
        'd' => 7}};
Vyom
  • 13
  • 3

1 Answers1

3

Say you had

my %h1 = ( a => 2, b => 3 );
my %h2 = ( c => 4, d => 7 );

To combine them into a third hash, you can use

my %h = ( %h1, %h2 );

It would be as if you had done

my %h = ( a => 2, b => 3, c => 4, d => 7 );

Any keys in common will be taken from the hash later in the list.


In your case, you have anonymous hashes. So where we would have used %NAME, we will use %BLOCK, where the block returns a reference to the hash we want to use. This gives us the following:

my %h_inner = (
   %{ $VAR1->{p} },
   %{ $VAR2->{p} },
);

This can also be written as follows:[1]

my %h_inner = (
   $VAR1->{p}->%*,
   $VAR2->{p}->%*,
);

Finally, you also want to second new hash with a single element keyed with p whose value is a reference to this first new hash.

my %h_outer = ( p => \%h_inner );

So, all together, you want

my %h_inner = (
   %{ $VAR1->{p} },
   %{ $VAR2->{p} },
);

my %h_outer = ( p => \%h_inner );

We could also use the anonymous hash constructor ({}) instead.

my %h_outer = (
   p => {
      %{ $VAR1->{p} },
      %{ $VAR2->{p} },
   },
};

Docs:


  1. Check version compatibility here.
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Hi, This is what I am getting with output. my %h1 = ( a => 2, b => 3 ); my %h2 = ( c => 4, d => 7 ); my %h = ( %h1, %h2 ); my %h = ( %{ $VAR1->{p} }, %{ $VAR2->{p} }, ); warn Dumper(%h); $VAR2 = 4; $VAR3 = 'a'; $VAR4 = 2; $VAR5 = 'b'; $VAR6 = 3; $VAR7 = 'd'; $VAR8 = 7 – Vyom Jun 02 '20 at 18:38
  • You are passing the keys and values to Dumper, just like you did to the assignment in the third statement. And, as you can see, they are the correct keys and values. That said, don't pass arrays and hashes to `Dumper`; pass references to them instead. You'll get something easier to read using `Dumper(\%h)`. – ikegami Jun 02 '20 at 18:45
  • Sorry but the p is gone in the output. {'a' => 2, 'b' => 3, 'c' => 4, 'd' => 7} – Vyom Jun 02 '20 at 18:48
  • Added to my answer. – ikegami Jun 02 '20 at 18:51