abhIta
abhIta

Reputation: 123

Comparing two hashes in perl using ne

I am trying to understand a piece of code in perl, but I am having some trouble with it being sort of new to perl programming.

I have two hashes, which are being input the same (key,value) pairs in the same order in different iterations of a for loop.

Iteration 1 creates %hash1, and Iteration 2 creates %hash2.

%hash1 = (1 => 10, 2 => 20, 3=> 30);

%hash2 = (1 => 10,  2 => 20, 3=> 30);

Then a command that compares these: goes as,

if (%hash1 ne %hash2) {print "Not Equal"; die;}

My question is:

(1) What exactly is compared in the above if statement?

(2) I tried assigning,

my $a = %hash1; my $b = %hash2;

But these give me outputs like 3/8! What could that be?

Any help would be greatly appreciated.

Upvotes: 2

Views: 1299

Answers (2)

rubber boots
rubber boots

Reputation: 15184

There is a Module Data::Compare available for comparing hashes on CPAN. This works as follows:

 use Data::Compare; # exports subroutine: Compare() !
 ...

 my %hash1 = (1 => 10, 2 => 20, 3 => 30);
 my %hash2 = (1 => 10, 2 => 20, 3 => 30);

 # This won't work:
 # if (%hash1 ne %hash2) {print "Not Equal"; die;}

 # This works:
 if( ! Compare(\%hash1, \%hash2)  ) {  print "Not Equal";  die; }

 ...

This is not a core module, you'll have to install it. It is also available under activeperl/windows (in their default repository).

Regards,

rbo

Upvotes: 0

ikegami
ikegami

Reputation: 385506

ne is the string comparison operator. It's operands are strings, and thus scalars. From perldata,

If you evaluate a hash in scalar context, it returns false if the hash is empty. If there are any key/value pairs, it returns true; more precisely, the value returned is a string consisting of the number of used buckets and the number of allocated buckets, separated by a slash.

So it's comparing that both hashes have the same number of used buckets and that both hashes have the same number of allocated buckets.

One way to compare the hashes would be to stringify them using JSON:XS with canonical set.

JSON::XS->new->canonical(1)->encode(\%hash)

Upvotes: 10

Related Questions