Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a simple Perl hash equivalence comparison?

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!

like image 943
cdleary Avatar asked Feb 12 '09 06:02

cdleary


People also ask

How do I create a hash reference in Perl?

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' };

How do I dereference a hash in Perl?

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.

How do I create an array of hashes in Perl?

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.

How do I traverse a hash in Perl?

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.


2 Answers

Something like cmp_deeply available in Test::Deep ?

like image 61
codelogic Avatar answered Oct 12 '22 11:10

codelogic


[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];
like image 42
Sergio Avatar answered Oct 12 '22 09:10

Sergio