in reply to Re: Comparing all keys in a hash
in thread Comparing all keys in a hash

If your going to go for the concatenated keys route, then it would be better to use a separator rather than null in the joins to prevent {AA=>1, B=>2} comparing equal to {A=>1, AB=>2}.

chr(28), the default value of $; is probably as good as any other. Usual caveats apply.

#! perl -slw use strict; sub cmp_hashes {local $"=$;; #" "@{[ sort keys %{$_[0]} ]}" cmp "@{[ sort keys %{$_[1]} ]}" } my %hashA = ( A=>1, B=>2, C=>3, D=>4 ); my %hashB = ( A=>1, B=>2, C=>3, D=>4 ); my %hashC = ( A=>1, C=>3, D=>4 ); my %hashD = ( A=>1, AB=>2, C=>3, D=>4, E=>5 ); my %hashE = ( AA=>1, B=>2, C=>3, D=>4, E=>5 ); print "hashA cmp hashB =>", cmp_hashes \%hashA, \%hashB; print "hashA cmp hashC =>", cmp_hashes \%hashA, \%hashC; print "hashA cmp hashD =>", cmp_hashes \%hashA, \%hashD; print "hashA cmp hashE =>", cmp_hashes \%hashA, \%hashE; print "hashB cmp hashC =>", cmp_hashes \%hashB, \%hashC; print "hashB cmp hashD =>", cmp_hashes \%hashB, \%hashD; print "hashB cmp hashE =>", cmp_hashes \%hashB, \%hashE; print "hashC cmp hashD =>", cmp_hashes \%hashC, \%hashD; print "hashC cmp hashE =>", cmp_hashes \%hashC, \%hashE; print "hashD cmp hashE =>", cmp_hashes \%hashD, \%hashE; __END__ C:\test>244656 hashA cmp hashB =>0 hashA cmp hashC =>-1 hashA cmp hashD =>1 hashA cmp hashE =>-1 hashB cmp hashC =>-1 hashB cmp hashD =>1 hashB cmp hashE =>-1 hashC cmp hashD =>1 hashC cmp hashE =>-1 hashD cmp hashE =>-1

Examine what is said, not who speaks.
1) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
2) The only way of discovering the limits of the possible is to venture a little way past them into the impossible
3) Any sufficiently advanced technology is indistinguishable from magic.
Arthur C. Clarke.

Replies are listed 'Best First'.
Re: Re: Re: Comparing all keys in a hash
by shotgunefx (Parson) on Mar 20, 2003 at 14:40 UTC
    slaps($self);
    Good catch. I actually did benchmark the two approaches and diotalevi's is around 25% faster on non matches and the string compare is about 14% faster when hashes match.

    -Lee

    "To be civilized is to deny one's nature."