【问题标题】:Comparing two hashes with the keys and values [closed]将两个哈希与键和值进行比较 [关闭]
【发布时间】:2013-04-07 11:38:42
【问题描述】:

我想比较两个散列,首先看看它们是否存在于第一个散列中,是否存在于第二个散列中,如果是,则比较值并打印成功,否则如果值不相等,则打印键具有不平等的价值。我已经解决了一些现有的类似问题,但这让我感到困惑。希望我能得到帮助。

【问题讨论】:

  • 请展示你到目前为止所做的尝试

标签: perl


【解决方案1】:

以下内容应该可以帮助您了解思路:

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";
    }
}

【讨论】:

  • 请记住,如果值是数字,您应该使用== 而不是eq
【解决方案2】:

如果您将此作为测试用例的一部分,那么您应该使用 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 的答案会更好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 2018-06-28
    • 2016-05-27
    • 1970-01-01
    • 2014-08-09
    • 2017-04-25
    • 2012-08-14
    相关资源
    最近更新 更多