如何打印@array2
但不是@array1
中存在的值?例如,给定:
@array1 = qw(1234567 7665456 998889 000909);
@array2 = qw(1234567 5581445 998889 000909);
输出应为:
5581445 doesn't exist in array1
答案 0 :(得分:6)
my %tmp ;
# Store all entries of array2 as hashkeys (values are undef) using a hashslice
@tmp{@array2} = undef ;
# delete all entries of array1 from hash using another hashslice
delete @tmp{@array1} ;
printf "In Array2 but not in Array1 : %s\n" , join( ',' , keys %tmp ) ;
答案 1 :(得分:2)
使用smart matching(从5.10开始)无需编译自己的数组条目表:
print "$_ doesn't exist in array1\n" foreach grep { not $_ ~~ @array1 } @array2;
答案 2 :(得分:0)
另一种方式是通过Array::Utils
:
use strict;
use warnings;
use Array::Utils qw(array_minus);
my @array1= qw(1234567 7665456 998889 000909);
my @array2= qw(1234567 5581445 998889 000909);
my @not_in_a1=array_minus(@array2,@array1);
if(@not_in_a1)
{
foreach(@not_in_a1)
{
print "$_ is in \@array2 but not in \@array1.\n";
}
}
else
{
print "Each element of \@array2 is also in \@array1.\n";
}
输出正是人们所期望的:
5581445 is in @array2 but not in @array1.