in reply to merge two hashes into one
map is useful here. The following example assumes that keys in both hashes are the same; ie. %h2 does not have any extra keys that %h1 doesn't have.
use strict; use Data::Dumper; my %h1 = (a => 1, b => 2, c => 3); my %h2 = (a => 6, b => 8, c => 0); my %h3 = map {$_ => $h1{$_} + $h2{$_}} keys %h1; print Dumper \%h3;
Output:
$VAR1 = { 'c' => 3, 'b' => 10, 'a' => 7 };
If %h2 does have keys that %h1 doesn't have, change this line:
my %h3 = map {$_ => $h1{$_} + $h2{$_}} keys %h1;
...to this:
my %h3 = map {$_ => $h1{$_} + $h2{$_}} keys %h1, keys %h2;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: merge two hashes into one
by AnomalousMonk (Archbishop) on May 30, 2018 at 01:23 UTC | |
by Tux (Canon) on May 30, 2018 at 11:24 UTC | |
by AnomalousMonk (Archbishop) on May 30, 2018 at 13:59 UTC |