How can I compare arrays in Perl?

后端 未结 12 2127
隐瞒了意图╮
隐瞒了意图╮ 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:18

    IMHO, you should use List::MoreUtils::pairwise. However, if for some reason you cannot, then the following sub would return a 1 for every index where the value in the first array compares equal to the value in the second array. You can generalize this method as much as you want and pass your own comparator if you want to, but at that point, just installing List::MoreUtils would be a more productive use of your time.

    use strict; use warnings;
    
    my @a = qw(abc def ghi jkl);
    my @b = qw(abc dgh dlkfj jkl kjj lkm);
    my $map = which_ones_equal(\@a, \@b);
    
    print join(', ', @$map), "\n";
    
    sub which_ones_equal {
        my ($x, $y, $compare) = @_;
        my $last = $#$x > $#$y ? $#$x : $#$y;
        no warnings 'uninitialized';
        return [ map { 0 + ($x->[$_] eq $y->[$_]) } $[ .. $last ];
    }
    

提交回复
热议问题