如何在不使用Data :: Compare的情况下比较Perl中的两个哈希值?

biz*_*nez 13 perl hash

如何在不使用Data :: Compare的情况下比较Perl中的两个哈希值?

FMc*_*FMc 22

最好的方法根据您的目的而有所不同.Sinan提到的FAQ项目是一个很好的资源:如何测试两个数组或哈希值是否相等?.在开发和调试期间(当然还有编写单元测试时),我发现Test::More在比较数组,散列和复杂数据结构时非常有用.一个简单的例子:

use strict;
use warnings;

my %some_data = (
    a => [1, 2, 'x'],
    b => { foo => 'bar', biz => 'buz' },
    j => '867-5309',
);

my %other_data = (
    a => [1, 2, 'x'],
    b => { foo => 'bar', biz => 'buz' },
    j => '867-5309x',
);

use Test::More tests => 1;
is_deeply(\%other_data, \%some_data, 'data structures should be the same');
Run Code Online (Sandbox Code Playgroud)

输出:

1..1
not ok 1 - data structures should be the same
#   Failed test 'data structures should be the same'
#   at _x.pl line 19.
#     Structures begin differing at:
#          $got->{j} = '867-5309x'
#     $expected->{j} = '867-5309'
# Looks like you failed 1 test of 1.
Run Code Online (Sandbox Code Playgroud)

  • 您已经在http://stackoverflow.com/questions/1274756/how-can-i-use-perls-testdeepcmpdeeply-without-increasing-the-test-count中询问了这一点.你没有回答为什么你不能增加测试的数量,或者你需要调用cmp_deeply三次的数据结构的复杂程度.请从您提出的问题中退一步,确定真正的问题是什么.如果您愿意提供更多信息,我们可以提供帮助. (5认同)
  • 看起来Test :: Deep的灵感来自is_deeply.我的问题是如何让cmp_deeply成为测试的一部分,而不是自己进行测试?因为我的测试列表只有8个,但每次我使用cmp_deeply时,它都算作测试,当我只有8个函数时,我的实际测试次数为11(因为我调用了cmp_deeply 3次).我不想增加测试次数.有更可行的解决方案吗? (2认同)

Cha*_*ens 10

在谈论哈希时,比较不是一个足够详细的短语.有很多方法可以比较哈希:

他们有相同数量的钥匙吗?

if (%a == %b) {
    print "they have the same number of keys\n";
} else {
    print "they don't have the same number of keys\n";
}
Run Code Online (Sandbox Code Playgroud)

两个哈希中的键是否相同?

if (%a != %b) {
    print "they don't have the same number of keys\n";
} else {
    my %cmp = map { $_ => 1 } keys %a;
    for my $key (keys %b) {
        last unless exists $cmp{$key};
        delete $cmp{$key};
    }
    if (%cmp) {
        print "they don't have the same keys\n";
    } else {
        print "they have the same keys\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

两个哈希中是否有相同的键和相同的值?

if (%a != %b) {
    print "they don't have the same number of keys\n";
} else {
    my %cmp = map { $_ => 1 } keys %a;
    for my $key (keys %b) {
        last unless exists $cmp{$key};
        last unless $a{$key} eq $b{$key};
        delete $cmp{$key};
    }
    if (%cmp) {
        print "they don't have the same keys or values\n";
    } else {
        print "they have the same keys or values\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

它们是同构的(我会把这个留给读者,因为我不特别想从头开始实现它)?

还是其他一些平等的衡量标准?

当然,这段代码只处理简单的哈希值.添加复杂的数据结构使其更加复杂.