in reply to multiple hash compare, find, create
Here's one way, although it does iterate over all three hashes twice. My brain hasn't quite kicked in yet this Monday morning, so I'm likely seriously overlooking a more efficient way to do it:
First, create a new temporary hash that has takes the count of keys, then using that new hash with the appropriate keys (the ones that have been counted at least three times), append the values from all three hashes into the new %combined hash:
use warnings; use strict; use Data::Dumper; my $num_hashes = 3; my %h1 = ( a => 1, b => 2, c => 3, ); my %h2 = ( a => 4, b => 5, d => 10, ); my %h3 = ( x => 20, p => 15, b => 6, a => 12, ); my %key_list; for my $hash (\%h1, \%h2, \%h3){ $key_list{$_}++ for keys %$hash; } my %combined; for my $hash (\%h1, \%h2, \%h3){ for (keys %key_list){ next if $key_list{$_} < $num_hashes; push @{ $combined{$_} }, $hash->{$_}; } } print Dumper \%combined;
Output:
$VAR1 = { 'b' => [ 2, 5, 6 ], 'a' => [ 1, 4, 12 ] };
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: multiple hash compare, find, create
by Eily (Monsignor) on Dec 10, 2018 at 18:54 UTC | |
by stevieb (Canon) on Dec 10, 2018 at 19:14 UTC | |
|
Re^2: multiple hash compare, find, create
by supertaco (Novice) on Dec 10, 2018 at 18:51 UTC |