2012-01-27 36 views
0

可能重复:
Comparing Two Arrays Using Perl如何找到在@数组2但不是在@值阵列1

如何打印存在于@array2值,但不@array1?例如,给定:

@array1 = qw(1234567 7665456 998889 000909); 
@array2 = qw(1234567 5581445 998889 000909); 

输出应该是:

5581445 doesn't exist in array1 
+0

仅供参考,这就是所谓的“相对补”(如果你只想要单程)或“对称差异“(如果你想要两种方式)集合论。这个问题似乎是重复的:http://stackoverflow.com/q/2933347 – derobert 2012-01-27 18:55:03

回答

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. 
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

没有必要自己编译阵列条目表,与smart matching(自5.10):

print "$_ doesn't exist in array1\n" foreach grep { not $_ ~~ @array1 } @array2; 
相关问题