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.