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

Re: Merge 2 hashes which contains duplicate Keys

by kennethk (Monsignor)
on Sep 25, 2012 at 19:17 UTC ( #995622=note: print w/ replies, xml ) Need Help??


in reply to Merge 2 hashes which contains duplicate Keys

What's going on in your initial code is when a duplicate key is encountered, you attempt to deference a string -- in the case of key one, you are accessing the non-existent variable @1. Your value then gets pushed onto @1, and not the hash element. The appropriate action is to test the values of the hash to see if they exist, and act accordingly, a la:

#!/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 ){ if (exists $h1{$x}) { $h1{$x} = [$h1{$x}, $h2{$x}] } else { $h1{$x} = $h2{$x}; } } print Dumper (\%h1);
In general, I find accessing data structures with inconsistent structure irritating and way too bug prone. Rather that varying structure based upon whether there is one or more value, I would make every hash entry an array reference, a la:
#!/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 %h1 ){ $h1{$x} = [$h1{$x}]; } foreach my $x ( keys %h2 ){ push @{$h1{$x}}, $h2{$x}; } print Dumper (\%h1);

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.


Comment on Re: Merge 2 hashes which contains duplicate Keys
Select or Download Code
Re^2: Merge 2 hashes which contains duplicate Keys
by slayedbylucifer (Scribe) on Sep 26, 2012 at 03:48 UTC
    Thanks kennethk. Your Explanation clarifies a lot of things for me. Thanks for your time.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2014-09-16 06:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (157 votes), past polls