I have two hashes which can contain the same keys. I am trying to merge the two hashes in such a way that if the key exists in both the hashes, I want to add the values in the respective hashes.
my %hash1= ();
$hash1{'apple'} = 10;
$hash1{'banana'} = 15;
$hash1{'kiwi'} = 20;
my %sourceHash = ();
$sourceHash{'apple'} = 12;
$sourceHash{'orange'} = 13;
$sourceHash{'banana'} = 5;
mergeHash(\%hash1, \%sourceHash);
sub mergeHash {
my $hash1 = shift;
my $hash2 = shift;
foreach my $key (keys %{$hash1})
{
if (exists $hash2->{$key}) {
${hash2}->{$key} = $hash1->{$key} + $hash2->{$key};
} else {
${hash2}->{$key} = $hash1->{$key};
}
}
}
I expect the result of hash1 to be
hash1{'apple'} = 22;
hash1{'orange'} = 13;
hash1{'banana'} = 20;
hash1{'kiwi'} = 20;
But I get an exception saying Can't modify constant item in scalar assignment. What am I doing wrong?