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

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

Hello Monks,

THis question is regarding merging two hashes with duplicate keys. I found few solutions on hte internet and they all work, but I could not understand any of them . Hence working it out on my own.

Also, I tried the Hash::Merge and it works too, but I am feeling that this is not really that diffuclt and hence want to do it myself.

Lets consider below 2 hashes:

my %h1 = ( "one" => 1, "two" => 2, "three" => 3, ); my %h2 = ( "four" => 4, "five" => 5, "six" => 6, "one" => 2222, );

I want to merge these two hash so that the resulting hash look like below:

$VAR1 = { 'one' => [ 1, 2222 ] 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5, 'six' => 6, };

So when a duplicate key is found, the value of that key should get into an anonymous array

I referred http://perldoc.perl.org/perlreftut.html and wrote below code:

#!/usr/bin/perl -w use strict; use Data::Dumper; my %h1 = ( "one" => 1, "two" => 2, "three" => 3, ); my %h2 = ( "four" => 4, "five" => 5, "six" => 6, "one" => 11111, ); foreach my $x ( keys %h2 ){ push @{ $h1{$x} }, $h2{$x}; } print Dumper (\%h1);

the output is:

Can't use string ("1") as an ARRAY ref while "strict refs" in use at s +lice_hash.pl line 48

So, I remove "use strict" and I get below output:

$VAR1 = { 'three' => 3, 'five' => [ 5 ], 'six' => [ 6 ], 'one' => 1, 'two' => 2, 'four' => [ 4 ] };

I am not able to figure out where I am going wrong. Any suggestions would be of great help.

Thanks.