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

后端 未结 7 1358
春和景丽
春和景丽 2020-12-10 03:08

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

相关标签:
7条回答
  • 2020-12-10 03:46

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

    Output:

    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.
    
    0 讨论(0)
提交回复
热议问题