用键和值比较两个哈希值



我想比较两个哈希值,首先看看第一个哈希值中的键是否存在于第二个哈希值中,如果存在,比较值并打印成功,否则如果值不相等,则打印具有不相等值的键。我已经浏览了一些现有的类似问题,但它让我感到困惑。

下面的内容应该可以帮助你获得一个想法:

for ( keys %hash1 ) {
    unless ( exists $hash2{$_} ) {
        print "$_: not found in second hashn";
        next;
    }
    if ( $hash1{$_} eq $hash2{$_} ) {
        print "$_: values are equaln";
    }
    else {
        print "$_: values are not equaln";
    }
}

如果你这样做作为测试用例的一部分,那么你应该使用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的答案更好。

最新更新