Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Comparing keys in 3 different hashes and if they are the same them print the values on one line

by Kenosis (Priest)
on Mar 01, 2013 at 05:40 UTC ( #1021157=note: print w/ replies, xml ) Need Help??


in reply to Comparing keys in 3 different hashes and if they are the same them print the values on one line

List::Compare can be helpful here. Just send the references to those three hashes to List::Compare's get_intersection method and it'll return the keys that those hashes have in common:

use strict; use warnings; use List::Compare; my %hash1 = ( A => 1, B => 2, C => 3, D => 4 ); my %hash2 = ( C => 30, D => 40, A => 10, B => 20 ); my %hash3 = ( F => 600, B => 200, A => 100, E => 500 ); my $lc = List::Compare->new( \%hash1, \%hash2, \%hash3 ); my @intersection = $lc->get_intersection; if (@intersection) { for my $key (@intersection) { print "\%hash1: $key => $hash1{$key}\n"; print "\%hash2: $key => $hash2{$key}\n"; print "\%hash3: $key => $hash3{$key}\n"; print "\n"; } } else { print "The three hashes don't share any common keys.\n"; }

Output:

%hash1: A => 1 %hash2: A => 10 %hash3: A => 100 %hash1: B => 2 %hash2: B => 20 %hash3: B => 200


Comment on Re: Comparing keys in 3 different hashes and if they are the same them print the values on one line
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (7)
As of 2014-12-27 06:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (176 votes), past polls