Beefy Boxes and Bandwidth Generously Provided by pair Networks Bob
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Comparing hashes without sorting the keys

by falsa_utopia (Initiate)
on Feb 19, 2004 at 21:15 UTC ( [id://330432]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


in reply to Comparing hashes without sorting the keys

Also for fun (and in my debut as a novice!):
#!/usr/bin/perl -w use strict; my %aa=(uno=>1, due=>2, tres => 3); my %bb=(due=>2, uno=>1, tres => 3); print comphash(\%aa, \%bb) ? "Hashes are equal\n" : "Hashes are differ +ent\n"; sub comphash { my ($aa, $bb) = @_; return 0 unless keys %$aa == keys %$bb; my %whole_hash = (%$aa, %$bb); my $different; foreach (keys %whole_hash) { next if exists $aa{$_} && exists $bb{$_} && $aa{$_} == $bb{$_} +; $different++ && last; } return not $different; }
Cheers!

Replies are listed 'Best First'.
Re: Re: Comparing hashes without sorting the keys
by BrowserUk (Patriarch) on Feb 19, 2004 at 22:40 UTC

    There are a few problems with that. If the hash values are not numeric your == will cause trouble. Switching that to eq will get you some way, but then values of '079' and '79' don't compare equal although they may be considered so for the applications use of them.

    Then you get into more esoteric problems. What if the values of the hash are themselves hashes or arrays (references). Comparing the stringyfied references will say that two arrays are different even if their contents is similar as they will have different addresses. Are two content-similar, but physically different arrays considered equal? That's almost a philisophical debate and very much depends on the application.

    That said. Many of these problem exists with most of the other solutions offered also.


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    Timing (and a little luck) are everything!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://330432]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.