本文介绍了如何在不使用Data :: Compare的情况下比较Perl中的两个哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I compare two hashes in Perl without using Data::Compare?

推荐答案

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

The best approach differs according to your purposes. The FAQ item mentioned by Sinan is a good resource: How do I test whether two arrays or hashes are equal?. During development and debugging (and of course when writing unit tests) I have found Test::More to be useful when comparing arrays, hashes, and complex data structures. A simple example:

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');

输出:

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.

这篇关于如何在不使用Data :: Compare的情况下比较Perl中的两个哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 20:10