in reply to Re: common keys in two hashes
in thread common keys in two hashes

But what about the keys in hash2? How will they be searched in hash1 to see if there are commons?

Replies are listed 'Best First'.
Re^3: common keys in two hashes
by toolic (Bishop) on Jan 09, 2008 at 18:09 UTC
    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
Re^3: common keys in two hashes
by alexm (Chaplain) on Jan 09, 2008 at 18:05 UTC
    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.
Re^3: common keys in two hashes
by WoodyWeaver (Monk) on Jan 09, 2008 at 20:16 UTC
    "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.