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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.