3 回答

TA貢獻1785條經驗 獲得超4個贊
另一種方法是使用Array :: Utils
use Array::Utils qw(:all);
my @a = qw( a b c d );
my @b = qw( c d e f );
# symmetric difference
my @diff = array_diff(@a, @b);
# intersection
my @isect = intersect(@a, @b);
# unique union
my @unique = unique(@a, @b);
# check if arrays contain same members
if ( !array_diff(@a, @b) ) {
# do something
}
# get items from array @a that are not in array @b
my @minus = array_minus( @a, @b );

TA貢獻1848條經驗 獲得超6個贊
perlfaq4 進行救援:
如何計算兩個數組的差?如何計算兩個數組的交集?
使用哈希。這是同時執行更多操作的代碼。假定每個元素在給定數組中都是唯一的:
@union = @intersection = @difference = ();
%count = ();
foreach $element (@array1, @array2) { $count{$element}++ }
foreach $element (keys %count) {
push @union, $element;
push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
}
如果正確聲明了變量,則代碼看起來更像以下內容:
my %count;
for my $element (@array1, @array2) { $count{$element}++ }
my ( @union, @intersection, @difference );
for my $element (keys %count) {
push @union, $element;
push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
}

TA貢獻1735條經驗 獲得超5個贊
您需要提供更多上下文。有更有效的方法可以做到:
走出Perl并使用shell(sort+ comm)
map一個數組放入Perl哈希,然后遍歷另一個數組,檢查哈希成員身份。這具有線性復雜度(“ M + N”-基本上循環遍歷每個數組一次),而嵌套循環則具有“ M * N”個復雜度)
例:
my %second = map {$_=>1} @second;
my @only_in_first = grep { !$second{$_} } @first;
# use a foreach loop with `last` instead of "grep"
# if you only want yes/no answer instead of full list
使用為您做最后一點的Perl模塊(注釋中提到了List :: Compare)
如果卷很大,則需要根據添加元素的時間戳進行操作,并且需要經常進行比較。幾千個元素還不夠大,但是我最近不得不比較10萬個列表。
添加回答
舉報