perl中两个数组的比较

Comparison of two arrays in perl

我正在尝试比较两个数组的内容,我需要最终输出为“匹配”或“不匹配” 我写了下面的代码,它给出了预期的输出。但是,任何人都可以建议我任何其他简单的方法吗

#!/usr/bin/perl
use strict;
use warnings;
 #Numeric scalar

my @array_1= (10,20,40,19);
my @array_2= (10,30,23,19);

print "@array_1\n";
my $count=0;
while ($count < scalar @array_1){
   for (@array_2) {
       if ($array_1[$count] == $array_2[$count]) {
        print "matched\n";
        $count++;} 
    else {
        print "Not matched\n";
        $count++;
        }
    }
    } 

先把不匹配的条件全部写下来,最后显示为匹配,很简单

#!/usr/bin/perl
use strict;
use warnings;

my @array_1 = (10,20,40,19);
my @array_2 = (10,30,23,19);

if (scalar @array_1 != scalar @array_2) {
  print "Not matched\n";
  exit 0;
}

while (my ($index, $elem) = each @array_1) {
  if ($elem != $array_2[$index]) {
    print "Not matched\n";
    exit 0;
  }
}

print "matched\n";

以上解决方案很好。您也可以使用 https://metacpan.org/pod/Array::Compare 模块

Array::Compare - Perl extension for comparing arrays. If you have two arrays and you want to know if they are the same or different, then Array::Compare will be useful to you. All comparisons are carried out via a comparator object.

use strict;
use warnings;
use Array::Compare;

my @array_1= (10,20,40,19);
my @array_2= (10,30,23,19,66);

my $comp = Array::Compare->new;

if ($comp->compare(\@array_1, \@array_2)) {
  print "Arrays are the same (Matched)\n";
} else {
  print "Arrays are different (Not Matched)\n";
}

Output

Arrays are different (Not Matched)