sub are_hashes_equal($$) {
my ($a, $b) = @_; # hashrefs
# number of keys in hashes must be the same
return 0 unless keys %$a == keys %$b;
# and each key-value pair in %$a must have an
# identical key-value pair in %$b
while (my ($key_a, $val_a) = each %$a) {
return 0 unless exists $b->{$key_a}
&& $b->{$key_a} eq $val_a;
}
return 1;
}
####
($a,$b) = ($b,$a) if keys %$b > keys %$a
####
use Test::LectroTest;
Property {
##[ h <- Hash( Int, Int ) ]##
are_hashes_equal( $h, $h ) == 1;
}, name => "equal hashes are recognized as equal";
Property {
##[ h <- Hash( Int, Int, length=>[1,] ) ]##
my %h_diff = %$h;
delete $h_diff{scalar each %$h}; # delete 1st key
are_hashes_equal( $h, \%h_diff ) == 0;
}, name => "differences in quantity of keys are detected";
Property {
##[ h <- Hash( Int, Int, length=>[1,] ) ]##
my %h_diff = %$h;
delete $h_diff{scalar each %$h}; # delete 1st key
$h_diff{a} = 1; # replace with "a" key
are_hashes_equal( $h, \%h_diff ) == 0;
}, name => "differences in values of keys are detected";
Property {
##[ h <- Hash( Int, Int, length=>[1,] ) ]##
my %h_diff = %$h;
$h_diff{scalar each %$h}++; # increment 1st value
are_hashes_equal( $h, \%h_diff ) == 0;
}, name => "differences in values are detected";
####
1..4
ok 1 - 'equal hashes are recognized as equal' (1000 attempts)
ok 2 - 'differences in quantity of keys are detected' (1000 attempts)
ok 3 - 'differences in values of keys are detected' (1000 attempts)
ok 4 - 'differences in values are detected' (1000 attempts)
####
#!/usr/bin/perl
# Tom Moertel 2004-10-12
use warnings;
use strict;
sub are_hashes_equal($$) {
my ($a, $b) = @_;
# number of keys in hashes must be the same
return 0 unless keys %$a == keys %$b;
# and each key-value pair in %$a must have an
# identical key-value pair in %$b
while (my ($key_a, $val_a) = each %$a) {
return 0 unless exists $b->{$key_a}
&& $b->{$key_a} eq $val_a;
}
return 1;
}
# we use LectroTest to test whether the following
# properties hold for our implementation above
use Test::LectroTest;
Property {
##[ h <- Hash( Int, Int ) ]##
are_hashes_equal( $h, $h ) == 1;
}, name => "equal hashes are recognized as equal";
Property {
##[ h <- Hash( Int, Int, length=>[1,] ) ]##
my %h_diff = %$h;
delete $h_diff{scalar each %$h}; # delete 1st key
are_hashes_equal( $h, \%h_diff ) == 0;
}, name => "differences in quantity of keys are detected";
Property {
##[ h <- Hash( Int, Int, length=>[1,] ) ]##
my %h_diff = %$h;
delete $h_diff{scalar each %$h}; # delete 1st key
$h_diff{a} = 1; # replace with "a" key
are_hashes_equal( $h, \%h_diff ) == 0;
}, name => "differences in values of keys are detected";
Property {
##[ h <- Hash( Int, Int, length=>[1,] ) ]##
my %h_diff = %$h;
$h_diff{scalar each %$h}++; # increment 1st value
are_hashes_equal( $h, \%h_diff ) == 0;
}, name => "differences in values are detected";