in reply to Compare two Hashes of Hashes
G'day Eshan_k,
"I am beginner in perl."
Yes, indeed. I strongly recommend that you read "perlintro -- Perl introduction for beginners". It's a fairly short read (under a dozen screenfuls on my monitor) and will take you through the basics. Perhaps more importantly, every section is peppered with links to more detailed discussions and advanced topics: it's a great reference source when your coding requirements become more complex.
The test data you posted has serious problems: you're assigning hashrefs to undeclared hashes which will end up having a single key, which looks something like "HASH(0x7fc1c3005498)", and a single undef value. The strict and warnings pragmata (both introduced at the start of perlintro) would have alerted you to this.
I see you've added additional information (the code you tried and the problem you had) in "Re^2: Compare two Hashes of Hashes". Consider this a reply to them both.
In the code below,
Here's my test code:
#!/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]} }
The output's a tad lengthy (65 lines). It's in the spoiler.
— Ken
|
|---|