Some of the offered answers seem wrong to me. If you want to add an element to the output hash only if the key exists in both inputs, I think that you would need something that is essentially this (tested) logic:
use strict; use warnings;
use Data::Dumper;
my $h1 = { 'a' => 1, 'b' => 2, 'c' => 3 };
my $h2 = { 'b' => 2, 'c' => 4, 'd' => 5 };
my $hout = {};
foreach my $k (keys $h1) {
if (exists $h2->{$k}) {
$hout->{$k} = $h1->{$k} + $h2->{$k};
}
}
print Data::Dumper->Dump([$hout], ['hout']);
$hout = {
'b' => 4,
'c' => 7
};
Loop through all of the keys in one hash and check to see if this key also exists in the other. If so, populate the output hash with the sum of the two.
Looking through the various answers, it seemed to me that some either modified $h1, or assumed that the key existed in $h2, or relied upon side effects. (Of course I did not down-vote any of them – I never do – and perhaps I am quite mistaken.)
Now, as far as “a good-looking, less-coded way,” the only criteria that really matters to me is that the logic is tested, that it is “at-a-glance obvious to anyone and everyone,” and that it is easy to maintain. If a future program-change requirement is to do different or additional things to the matching elements, it should be easy to make that modification without breaking what’s there. I place no premium on brevity – quite the opposite. (My career experience commonly deals with software that is dozens of years old and built by a great many someone-elses, so I am very keen to such concerns.)