#!/usr/bin/env perl -l use strict; use warnings; { my @tests = ( { x => { a => 1, b => 2 }, y => { c => 3} }, { x => { a => 1, b => 2 }, z => { c => 3} }, { x => { a => 1, b => 2 }, y => { c => 3}, z => {} }, { x => { a => 1, b => 2 }, y => { c => 3, d => 4 } }, { x => { a => 1, b => 2 }, y => { d => 3} }, { x => { a => 1, d => 2 }, y => { c => 3} }, { x => { a => 1, b => 2 }, y => { c => 4} }, ); for (0 .. $#tests) { print "Comparing \$tests[0] with \$tests[$_]"; comp($tests[0], $tests[$_]); print '-' x 40; } } sub comp { my ($h1, $h2) = @_; return unless comp_keys($h1, $h2); for (sort keys %$h1) { print "Comparing keys in '$_' hashref."; return unless comp_keys($h1->{$_}, $h2->{$_}); print "Comparing values in '$_' hashref."; return unless comp_vals($h1->{$_}, $h2->{$_}); } } sub comp_keys { my ($h1, $h2) = @_; my @keys = ([sort keys %$h1], [sort keys %$h2]); if (@{$keys[0]} == @{$keys[1]}) { print "Same number of keys."; if (ary2str($keys[0]) eq ary2str($keys[1])) { print "Same keys."; } else { print "Different keys."; return 0; } } else { print "Different number of keys."; return 0; } return 1; } sub comp_vals { my ($h1, $h2) = @_; my @keys = sort keys %$h1; if (ary2str([@$h1{@keys}]) eq ary2str([@$h2{@keys}])) { print "Same values"; } else { print "Different values"; return 0; } return 1; } sub ary2str { join $;, @{$_[0]} } #### Comparing $tests[0] with $tests[0] Same number of keys. Same keys. Comparing keys in 'x' hashref. Same number of keys. Same keys. Comparing values in 'x' hashref. Same values Comparing keys in 'y' hashref. Same number of keys. Same keys. Comparing values in 'y' hashref. Same values ---------------------------------------- Comparing $tests[0] with $tests[1] Same number of keys. Different keys. ---------------------------------------- Comparing $tests[0] with $tests[2] Different number of keys. ---------------------------------------- Comparing $tests[0] with $tests[3] Same number of keys. Same keys. Comparing keys in 'x' hashref. Same number of keys. Same keys. Comparing values in 'x' hashref. Same values Comparing keys in 'y' hashref. Different number of keys. ---------------------------------------- Comparing $tests[0] with $tests[4] Same number of keys. Same keys. Comparing keys in 'x' hashref. Same number of keys. Same keys. Comparing values in 'x' hashref. Same values Comparing keys in 'y' hashref. Same number of keys. Different keys. ---------------------------------------- Comparing $tests[0] with $tests[5] Same number of keys. Same keys. Comparing keys in 'x' hashref. Same number of keys. Different keys. ---------------------------------------- Comparing $tests[0] with $tests[6] Same number of keys. Same keys. Comparing keys in 'x' hashref. Same number of keys. Same keys. Comparing values in 'x' hashref. Same values Comparing keys in 'y' hashref. Same number of keys. Same keys. Comparing values in 'y' hashref. Different values ----------------------------------------