http://www.perlmonks.org?node_id=157719

Rajiv has asked for the wisdom of the Perl Monks concerning the following question: (hashes)

Perl Monks, Please Suggest: How can i find whether two hash tables have same and equal number of keys.

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How to check similarity of two hash tables
by RMGir (Prior) on Apr 09, 2002 at 14:21 UTC
    Of course, the obligatory one-liner (ok, one-expression) version:
    my $areEqual = (keys %hash1 == keys %hash2) && 0 == grep {!exists $hash2{$_}} keys %hash1;
Re: How to check similarity of two hash tables
by RMGir (Prior) on Apr 09, 2002 at 14:11 UTC
    They're equal if, as you say, they have the same number of keys AND all the keys in one are in the other.
    my $areEqual=1; if(keys %hash1 == keys %hash2) { foreach my $key(keys %hash1) { if(!exists $hash2{$key}) { $areEqual=0; last; } } } if($areEqual) { print "ARE "; } else { print "ARE NOT "; } print "equal\n";