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

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

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

7条回答
  •  不思量自难忘°
    2020-12-10 03:35

    Compare is not a detailed enough phrase when talking about hashes. There are many ways to compare hashes:

    Do they have the same number of keys?

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

    Are the keys the same in both hashes?

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

    Do they have the same keys and the same values in both hashes?

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

    Are they isomorphic (I will leave this one up to the reader as I don't particularly want to try implementing it from scratch)?

    Or some other measure of equal?

    And, of course, this code only deals with simple hashes. Adding complex data structures makes it even more complex.

提交回复
热议问题