in reply to Merging two hashes, keeping keys unique but adding values if necessary
update : i appologize por posting accidently into the wrong window
well you were almost there. here is a version utilizing your approach:
however, if you are biginner, do not go exploring functions like map until you master "for", "while" and "foreach" loop. Thus equivalent to your proposed solution is :use strict; use Data::Dumper; %muthash = ( key1 => '1', key15 => '3', key150 => '1', ); %copyhash =( key1 => '1', key15 => '1', key140 => '1', ); %mergedhash = (); %mergedhash = map {$_=> $muthash{$_} + $copyhash{$_}; } (keys %muthash +, keys %copyhash); print Dumper(\%mergedhash);
cheersmy %muthash = ( "key1" => 1, "key15" => 3, "key150" => 1 ); my %copyhash = ( "key1" => 1, "key15" => 1, "key140" => 1 ); my %mergedhash; foreach (keys %muthash){ $mergedhash{$_} = $muthash{$_}+ $copyhash{$_}; } foreach (keys %copyhash){ $mergedhash{$_} = $muthash{$_}+ $copyhash{$_} unless defined $mergedha +sh{$_}; } print Dumper(\%mergedhash);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Merging two hashes, keeping keys unique but adding values if necessary
by LanX (Saint) on Jun 04, 2014 at 16:04 UTC |