简体   繁体   中英

Perl: Combine hash with Keys of Keys containing identical Key

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM