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!
Write the hash syntax as you would have without references, and then replace the name of the hash with a pair of curly braces surrounding the thing holding the reference. For example, to pick a particular value for a given key, use: my $name = $ gilligan_info { 'name' }; my $name = $ { $hash_ref } { 'name' };
Dereference a HASH First we print it out directly so you can see it is really a reference to a HASH. Then we print out the content using the standard Data::Dumper module. Then we de-reference it by putting a % sign in-front of it %$hr and copy the content to another variable called %h.
To add another hash to an array, we first initialize the array with our data. Then, we use push to push the new hash to the array. The new hash should have all of its data. As shown below, you can see the difference between the two arrays before and after pushing a new hash.
Perl hash question: How do I traverse the elements of a hash in Perl? Answer: There are at least two ways to loop over all the elements in a Perl hash. You can use either (a) a Perl foreach loop, or (b) a Perl while loop with the each function.
Something like cmp_deeply available in Test::Deep ?
[This was a response to an answer by someone who deleted their answer.]
Uh oh!
%a ~~ %b && [sort values %a] ~~ [sort values %b]
doesn't check whether the values belong to the same keys.
#! perl
use warnings;
use strict;
my %a = (eat => "banana", say => "whu whu"); # monkey
my %b = (eat => "whu whu", say => "banana"); # gorilla
print "Magilla Gorilla is always right\n"
if %a ~~ %b && [sort values %a] ~~ [sort values %b];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With