Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Comparing hashes without sorting the keys

by Popcorn Dave (Abbot)
on Feb 18, 2004 at 20:38 UTC ( [id://330051]=note: print w/replies, xml ) Need Help??


in reply to Comparing hashes without sorting the keys

This seems a bit of work to do strictly in Perl, but this should do what you want to do. However I do believe that davido's suggestion of the module is cleaner to work with as you're not doing the conversion of the hash to a sorted array, then to a string.

#!/usr/bin/perl/ use strict; my %aa=(uno=>1, due=>2); my %bb=(due=>2, uno=>1); my ($aa,$bb,@aa,@bb); **updated** @aa=sort(%aa); @bb=sort(%bb); $aa = join("",@aa); $bb = join("",@bb); **updated if ($aa eq $bb){ print "Matches!\n"; } else{ print "No match!\n"; }

Update: As both samtregar and <a href="http://www.perlmonks.org/index.pl?node_id=56270>greenFox point out the original code blows up with the data they show in their nodes. However replacing the

@aa=%aa; @bb=%bb; $aa = join("",sort @aa); $bb = join("", sort @bb);

with

@aa=sort(%aa); @bb=sort(%bb); $aa = join(" ",@aa); $bb = join(" ",@bb);

I believe should do what I originally intended.

Sorting the hash, not the array, and leaving the space in should solve the problem found by the other monks.

There is no emoticon for what I'm feeling now.

Replies are listed 'Best First'.
Re: Re: Comparing hashes without sorting the keys
by samtregar (Abbot) on Feb 18, 2004 at 23:25 UTC
    That won't work! Try it on these hashes, which your code considers equal, for example:

    my %aa=(aa=>'aa', bb=>'bb'); my %bb=(a=>'aaa', b=>'bbb');

    -sam

      ++nicely spotted. Even just "flattening" the hash to an array is suicidal, consider
      my %aa=(aa=>'bb', cc=>'dd'); my %bb=(bb=>'aa', dd=>'cc');
      ...ouch!

      --
      Do not seek to follow in the footsteps of the wise. Seek what they sought. -Basho

      You're right! Given the OP's data I just hacked out a quick solution, but thanks for pointing out my flaw.

      Good call.

      There is no emoticon for what I'm feeling now.

Re: Re: Comparing hashes without sorting the keys
by samtregar (Abbot) on Feb 19, 2004 at 18:04 UTC
    Your new code won't work either! Try it with:

    my %aa=(aa=>'a aa'); my %bb=(a=>'aa aa');

    -sam

      Okay, I give. :)

      svsingh pointed out the same thing to me. Like I said originally, the best way to do it is with the module and the hash reference.

      There is no emoticon for what I'm feeling now.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://330051]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2024-04-19 14:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found