in reply to Merge 2 hashes which contains duplicate Keys
You cannot push a second value onto a key that already exists and has a scalar value, because the first value is a scalar, not an array (ref).
So you need to remove that value, replace it with an array ref, and then push the original value + the second value into that array.
#!/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 } ) { my $temp = delete $h1{ $x }; push @{ $h1{$x} }, $temp , $h2{ $x }; } else { $h1{ $x } = $h2{ $x }; } } print Dumper (\%h1);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Merge 2 hashes which contains duplicate Keys
by slayedbylucifer (Scribe) on Sep 26, 2012 at 04:38 UTC | |
by BrowserUk (Patriarch) on Sep 26, 2012 at 05:24 UTC |