Comparing two hashes with keys and values

I want to compare two hashes, first see if a key that is in the 1st hash exists in the second hash, and if it compares the values ​​and print success, if the values ​​are not equal, print a key that has a different value. I went through some existing similar questions, but it bothers me. I hope I can get help.

0
source share
2 answers

The following should help you understand:

for ( keys %hash1 ) { unless ( exists $hash2{$_} ) { print "$_: not found in second hash\n"; next; } if ( $hash1{$_} eq $hash2{$_} ) { print "$_: values are equal\n"; } else { print "$_: values are not equal\n"; } } 
+6
source

If you do this as part of a test case, then you should use Test::More is_deeply , which will compare two complex data structure references together and print where they differ.

 use Test::More; $a = { a => [ qw/abc/ ], b => { a => 1, b =>2 }, c => 'd' }; $b = { a => [ qw/abc/ ], b => { a => 2, b =>2 }}; is_deeply($a, $b, 'Testing data structures'); not ok 1 - Testing data structures # Failed test 'Testing data structures' # at - line 4. # Structures begin differing at: # $got->{c} = 'd' # $expected->{c} = Does not exist # Tests were run but no plan was declared and done_testing() was not seen. 

If you need to do this in code, then @Alan Haggai Alavi's answer is better.

+1
source

All Articles