in reply to Merge 2 hashes which contains duplicate Keys
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 %h2 ){ if (exists $h1{$x}) { $h1{$x} = [$h1{$x}, $h2{$x}] } else { $h1{$x} = $h2{$x}; } } print Dumper (\%h1);
#!/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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Merge 2 hashes which contains duplicate Keys
by slayedbylucifer (Scribe) on Sep 26, 2012 at 03:48 UTC |