in reply to Re^2: merge two hashes into one
in thread merge two hashes into one

my %h1 = qw( a 1 b 2 c 3 ); my %h2 = qw( b 7 c 8 d 4 ); my %h3 = map { $_ => $h1{$_} // 0 + $h2{$_} // 0 } keys %h1, keys %h2;

No warnings, merges both hashes


Enjoy, Have FUN! H.Merijn

Replies are listed 'Best First'.
Re^4: merge two hashes into one
by AnomalousMonk (Archbishop) on May 30, 2018 at 13:59 UTC

    The expression  $h1{$_} // 0 + $h2{$_} // 0 has a complicated precedence:

    c:\@Work\Perl\monks>perl -wMstrict -MO=Deparse,-p -le "my %h1 = qw( a 1 b 2 c 3 ); my %h2 = qw( b 7 c 8 d 4 ); my %h3 = map { $_ => $h1{$_} // 0 + $h2{$_} // 0 } keys %h1, keys %h2 +; " BEGIN { $^W = 1; } BEGIN { $/ = "\n"; $\ = "\n"; } use strict 'refs'; (my(%h1) = ('a', '1', 'b', '2', 'c', '3')); (my(%h2) = ('b', '7', 'c', '8', 'd', '4')); (my(%h3) = map({($_, (($h1{$_} // (0 + $h2{$_})) // 0));} keys(%h1), k +eys(%h2))); -e syntax OK
    Are you sure it works in all circumstances? Wouldn't it be better to throw in a couple pair disambiguating parentheses? E.g.:
        ($h1{$_} // 0) + ($h2{$_} // 0)


    Give a man a fish:  <%-{-{-{-<