in reply to common keys in two hashes

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

Replies are listed 'Best First'.
Re^2: common keys in two hashes
by Anonymous Monk on Jan 09, 2008 at 17:58 UTC
    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.