Beefy Boxes and Bandwidth Generously Provided by pair Networks Bob
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Comparing hashes without sorting the keys

by demerphq (Chancellor)
on Feb 20, 2004 at 10:56 UTC ( [id://330569]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


in reply to Comparing hashes without sorting the keys

use strict; use warnings; use Data::Dumper; sub are_hashes_equal { my ($hash1,$hash2)=@_; return 1 if $hash1==$hash2; my %temp=%$hash2; foreach my $key (keys %$hash1) { return 0 unless exists $temp{$key} and defined($hash1->{$key}) eq defined($temp{$key}) and (defined $temp{$key} ? $temp{$key} eq $hash1->{$ke +y} : 1); delete $temp{$key}; } return !keys(%temp); } my %aa=(uno=>1, due=>2,trio=>undef,quat=>0,cinq=>''); my @b=( \%aa, {uno=>1, due=>2,trio=>undef,quat=>0,cinq=>''}, {uno=>1, due=>2,trio=>0,quat=>undef,cinq=>''}, {uno=>2, due=>2,trio=>undef,quat=>0,cinq=>''}, {uno=>2, due=>2,trio=>undef,quat=>0}, {uno=>2, due=>2,trio=>undef,quat=>0,cinq=>'',sex=>'is fun'}, ); print Data::Dumper->Dump([\%aa],['*aa']); foreach my $test_id (0..$#b) { print Data::Dumper->Dump([$b[$test_id]],['*test'.$test_id]); print "Is ",(are_hashes_equal(\%aa,$b[$test_id]) ? '' : 'not '), "the same as %aa\n\n"; }

produces

%aa = ( 'cinq' => '', 'trio' => undef, 'due' => 2, 'uno' => 1, 'quat' => 0 ); %test0 = ( 'cinq' => '', 'trio' => undef, 'due' => 2, 'uno' => 1, 'quat' => 0 ); Is the same as %aa %test1 = ( 'cinq' => '', 'trio' => undef, 'due' => 2, 'uno' => 1, 'quat' => 0 ); Is the same as %aa %test2 = ( 'cinq' => '', 'trio' => 0, 'due' => 2, 'uno' => 1, 'quat' => undef ); Is not the same as %aa %test3 = ( 'cinq' => '', 'trio' => undef, 'due' => 2, 'uno' => 2, 'quat' => 0 ); Is not the same as %aa %test4 = ( 'trio' => undef, 'due' => 2, 'uno' => 2, 'quat' => 0 ); Is not the same as %aa %test5 = ( 'cinq' => '', 'trio' => undef, 'due' => 2, 'uno' => 2, 'sex' => 'is fun', 'quat' => 0 ); Is not the same as %aa

HTH


---
demerphq

    First they ignore you, then they laugh at you, then they fight you, then you win.
    -- Gandhi


Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://330569]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.