I needed to be able to check that two hashes have the same contents as part of a test suite. A Super Search turned up How to test equality of hashes? which has answers for the equality bit, but doesn't address the reporting bit.
The following code uses List::Compare::Functional to assist in comparing two hashes and reporting differences between them. Note that the application specific warning strings may need to be adjusted for your context. :-)
use List::Compare::Functional qw(get_unique get_complement); sub hashesEqual { my ($have, $want) = @_; my @keysHave = sort keys %$have; my @keysWant = sort keys %$want; my @haveOnly = get_unique ([\@keysHave, \@keysWant]); my @wantOnly = get_complement ([\@keysHave, \@keysWant]); if (@haveOnly) { warn 'Unexpected parameters ' . (join ',', @haveOnly) . " for +email send\n"; return; } if (@wantOnly) { warn 'Expected parameters ' . (join ',', @haveOnly) . " missin +g for email send\n"; return; } my $ok = 1; for (@keysHave) { next if $have->{$_} eq $want->{$_}; $ok = undef; warn "Email send parameter $_ expected '$want->{$_}', got '$ha +ve->{$_}'\n"; } return $ok; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Testing hash equality and reporting differences
by davidrw (Prior) on Oct 18, 2006 at 23:30 UTC | |
by GrandFather (Saint) on Oct 18, 2006 at 23:31 UTC |