Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello monks!
I want to find the common keys in two hashes.
I found this code in perlfaq:
my @common = (); foreach (keys %hash1) { push(@common, $_) if exists $hash2{$_}; } # @common now contains common keys
but I wanted to ask, does this code check also if any key of hash2 is in hash1? Or must I write it again so as to get the keys of hash2 that are present in hash1?
Thank you!

Replies are listed 'Best First'.
Re: common keys in two hashes
by olus (Curate) on Jan 09, 2008 at 17:32 UTC
    This code runs through all the keys in hash1 so there is nothing more to do.
    Even if hash2 has more keys than hash1, they will not be matched in hash1
      But what about the keys in hash2? How will they be searched in hash1 to see if there are commons?
        Experimenting on your own will prove that only one search is needed. You did try this out on your own, didn't you? Anyway, here is a simple example where the common keys are b and c:
        #!/usr/bin/env perl use warnings; use strict; my %hash1 = (a=>1,b=>2,c=>3,d=>4); my %hash2 = ( b=>5,c=>6, e=>7); my @common = (); foreach (keys %hash1) { push(@common, $_) if exists $hash2{$_}; } # @common now contains common keys print "common1: @common\n"; @common = (); # empty the array # reverse the search: foreach (keys %hash2) { push(@common, $_) if exists $hash1{$_}; } print "common2: @common\n";

        prints:

        common1: c b common2: c b
        As olus said, you don't need to search keys in %hash2 because you already found all those being also keys in %hash1. Any key from %hash2 which is not in @common won't be in %hash1 either.
        "common" would mean that they are in both, so you could iterate over one (the smaller one) and check via the hash for existence in the other.