I'm wondering if there's an idiomatic one-liner or a standard-distribution package/function that I can use to compare two Perl hashes with only builtin, non-blessed types. The hashes are not identical (they don't have equivalent memory addresses).
I'd like to know the answer for both for shallow hashes and hashes with nested collections, but I understand that shallow hashes may have a much simpler solution.
TIA!
For shallow hashes:
hashes can be casted into arrays, where every value follows its key (but you won't know the order of the keys). So:
Oh, wait, that won't work because there are some edge cases, like:
So it's best to use a character in the join() that you KNOW will never appear in any key or value. If the values are BLOBs, that will be a big problem, but for anything else you could use the NULL char "\0".
Looks kinda ugly, I know, but it will do for checking if two hashes are equal in a shallow way, which is what most people are looking for.
I don't know if there's an easy way or a built-in package, and I don't know what happens when you just do
%hash1 == %hash2
(but that's probably not it), but it's not terribly hard to roll your own:Untested, but should return 0 if the hashes have all the same elements and all the same values. This function will have to be modified to account for multidimensional hashes.
If you want something from a standard distribution, you could
use Data::Dumper;
and just dump the two hashes into two scalar variables, then compare the strings for equality. That might work.There's also a package on CPAN called
FreezeThaw
that looks like it does what you want.Note that to use the smart match (not repeated here because it's already posted), you will have to
use feature;
and it's only available for Perl 5.10. But who's still using Perl 5.8.8, right?Thanks for your question.
I used Test::More::eq_hash as result.
convert hashes to xml files and compare, and yes you could use multilevel.
[This was a response to an answer by someone who deleted their answer.]
Uh oh!
doesn't check whether the values belong to the same keys.