Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: merge two hashes into one

by jdporter (Canon)
on May 30, 2018 at 17:06 UTC ( #1215483=note: print w/replies, xml ) Need Help??


in reply to merge two hashes into one

My solution, designed to take any number of hashes, not just two. Encapsulated in a function named add_hashes. Uses some functions in List::Util.

use List::Util qw( sum uniq ); # pass list of hashrefs. # returns a hash (list). sub add_hashes(@) { map { my $k = $_; $k => sum( map $_->{$k}, @_ ) } uniq( map keys(%$_), @_ ) }
Test it:
my %h1 = map { ( $_ => 1 ) } qw( a b c d e f g h ); my %h2 = map { ( $_ => 1 ) } qw( b c d e f g h i ); my %h3 = map { ( $_ => 1 ) } qw( c d e f g h i j ); my %h4 = map { ( $_ => 1 ) } qw( d e f g h i j k ); my %summed = add_hashes( \%h1, \%h2, \%h3, \%h4, ); use Data::Dumper; $Data::Dumper::Sortkeys=1; print Dumper \%summed;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1215483]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2019-04-22 12:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I am most likely to install a new module from CPAN if:
















    Results (112 votes). Check out past polls.

    Notices?