Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Comparing hashes without sorting the keys

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


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 20, 2004 at 03: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
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (6)
As of 2024-04-19 11:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found