我想比较两个哈希值,首先看看它们是否存在于第一个哈希值中,是否存在于第二个哈希值中,如果是这样比较值并打印成功,如果值不相等,则打印键具有不平等的价值。我已经经历了一些类似的问题,但它让我感到困惑。希望我可以得到帮助。
答案 0 :(得分:6)
以下内容可以帮助您了解一下:
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";
}
}
答案 1 :(得分:1)
如果您在测试用例中执行此操作,则应使用Test::More
is_deeply
将两个复杂的数据结构引用进行比较,并打印它们不同的位置。
use Test::More;
$a = { a => [ qw/a b c/ ], b => { a => 1, b =>2 }, c => 'd' };
$b = { a => [ qw/a b c/ ], 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.
如果您需要在代码中执行此操作,那么@Alan Haggai Alavi的答案会更好。