
BillKSmith
Veteran
May 1, 2017, 10:45 AM
Post #3 of 3
(999 views)
|
Re: [rietchel] Better way to compare two hashes
[In reply to]
|
Can't Post
|
|
Your looping is much to complex to accomplish what you do. Use:
use strict; use warnings; my %first_hash = ( "foo_1" => "bar_1", "foo_2" => "bar_2", "foo_3" => "bar_3", ); my %second_hash = ( "foo_1" => "bar_1", "foo_2" => "bar_2", "foo_3" => "ERR", #"foo_3" => "bar_3", ); foreach my $key (keys %first_hash) { if ( $first_hash{$key} eq $second_hash{$key} ) { printf "Matching: First Val: %5s Second Val: %5s\n", $first_hash{$key}, $second_hash{$key}; } else{ printf "Mismatching: First Val: %5s Second Val: %5s\n", $first_hash{$key}, $second_hash{$key}; } } If you really want all the printing, I would not recommend map or grep. If you only need to know whether or not the hashes match, you could use grep. However the logic is much clearer if you use a grep-like function from the module List::MoreUtils.
use strict; use warnings; use List::MoreUtils qw(all); my %first_hash = ( "foo_1" => "bar_1", "foo_2" => "bar_2", "foo_3" => "bar_3", ); my %second_hash = ( "foo_1" => "bar_1", "foo_2" => "bar_2", "foo_3" => "ERR", #"foo_3" => "bar_3", ); my $match = all {$first_hash{$_} eq $second_hash{$_} } keys %first_hash; die "Hashes do not match\n" if (!defined $match); print "Hashes do match\n"; Your method and mine only work correctly when the hashes contain the same set of keys. If not, You must specify exactly what you want before you can code the test. Probably the best way to generalize to a hash of hashes is to use a recursive subroutine. Good Luck, Bill
|