Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: How to test equality of hashes?

by bikeNomad (Priest)
on Jun 20, 2001 at 06:55 UTC ( [id://89901]=note: print w/replies, xml ) Need Help??


in reply to How to test equality of hashes?

Another way to compare (possibly arbitrarily deep) hashes is to stringify them using Storable and then compare the strings:
use Storable 'freeze'; $Storable::canonical = 1; if (freeze(\%hash1) eq freeze(\%hash2)) { # they're equal }
However, both this and the prior version I suggested suffer from a potential problem having to do with floating point accuracy and the stringification of numbers. Be warned. If you're not using numbers, both will work OK.

Replies are listed 'Best First'.
Re: Re: How to test equality of hashes?
by Brovnik (Hermit) on Jun 20, 2001 at 12:42 UTC
    But, see the following from perldoc Storable

    Setting "$Storable::canonical" may not yield frozen strings that compare equal due to possible stringification of numbers. When the string version of a scalar exists, it is the form stored, therefore if you happen to use your numbers as strings between two freezing operations on the same data structures, you will get different results.

    --
    Brovnik
Re:{2} How to test equality of hashes?
by jeroenes (Priest) on Jun 20, 2001 at 18:40 UTC
    There is no way Storable can garantee the order of your hashes. You could use slices to assure an order, but that doesn't work for nested structures. Moreover, only references to objects are allowed, destroying the order of the slices.

    Update: Missed a part of the Storable manpage. Ignore my comment please

      I'm not sure what you're saying. I'm not expecting Storable to guarantee anything other than that it'll serialize hashes by sorted key order, which is what setting $Storable::canonical to true is supposed to do. From the Storable manpage:

      If you set $Storable::canonical to some TRUE value, Storable will store hashes with the elements sorted by their key. This allows you to compare data structures by comparing their frozen representations (or even the compressed frozen representations), which can be useful for creating lookup tables for complicated queries.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2024-04-24 17:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found