How can I compare arrays in Perl?

后端 未结 12 2118
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 18:54

I have two arrays, @a and @b. I want to do a compare among the elements of the two arrays.

my @a = qw\"abc def efg ghy klm ghn\";
m         


        
12条回答
  •  生来不讨喜
    2020-12-06 19:09

    First of all, your 2 arrays need to be written correctly.

    @a = ("abc","def","efg","ghy","klm","ghn");
    @b = ("def","efg","ghy","klm","ghn","klm");
    

    Second of all, for arbitrary arrays (e.g. arrays whose elements may be references to other data structures) you can use Data::Compare.

    For arrays whose elements are scalar, you can do comparison using List::MoreUtils pairwise BLOCK ARRAY1 ARRAY2, where BLOCK is your comparison subroutine. You can emulate pairwise (if you don't have List::MoreUtils access) via:

    if (@a != @b) {
        $equals = 0;
    } else {
        $equals = 1;
        foreach (my $i = 0; $i < @a; $i++) {
            # Ideally, check for undef/value comparison here as well 
            if ($a[$i] != $b[$i]) { # use "ne" if elements are strings, not numbers
                                    # Or you can use generic sub comparing 2 values
                $equals = 0;
                last;
            }
        }
    }
    

    P.S. I am not sure but List::Compare may always sort the lists. I'm not sure if it can do pairwise comparisons.

提交回复
热议问题