in reply to Merging two hashes, keeping keys unique but adding values if necessary

sorry wrong code

update : i appologize por posting accidently into the wrong window

well you were almost there. here is a version utilizing your approach:

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);
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 :
my %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);
cheers

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
    you are using the values from one hash as keys for the other one !?!

    update

    and in your updated version the key/values unique to the %copyhash (like key140 ) will be missing.

    Cheers Rolf

    (addicted to the Perl Programming Language)