2012-01-27 39 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; 
相關問題