有几种方法可以做到这一点,这也取决于具体需要什么。
对每个数组使用辅助哈希,将存在检查减少为查找
use warnings;
use strict;
use feature 'say';
sub diff_arys {
my ($ra1, $ra2) = @_;
my %in_a1 = map { $_ => 1 } @$ra1;
my %in_a2 = map { $_ => 1 } @$ra2;
my @not_in_one = grep { not exists $in_a1{$_} } @$ra2;
my @not_in_two = grep { not exists $in_a2{$_} } @$ra1;
return (@not_in_one ? \@not_in_one : undef),
(@not_in_two ? \@not_in_two : undef);
}
my @ary1 = 'a'..'e'; # a,b,c,d,e
my @ary2 = ('a'..'d', 'z'); # a,b,c,d, z
my ($not_in_one, $not_in_two) = diff_arys(\@ary1, \@ary2);
say "@$not_in_one" if $not_in_one;
say "@$not_in_two" if $not_in_two;
Prints
z
e
这会发现两种方式的差异,一个数组中的元素,但另一个数组中的元素则不然。如果您实际上知道您只需要它用于一个“方向”,以识别第一个数组中但不在第二个数组中的内容(从问题看来),那么调整子以便仅获得所需的返回。然后代码就更少了,你可以只返回数组(所以,一个列表或空)
注意接口的选择:Returnundef
如果没有发现差异,则返回 arrayref。
对于此类工作有很好的模块。比较全面的一个是列表::比较 https://metacpan.org/pod/List::Compare。还有数组::实用工具 https://metacpan.org/pod/Array::Utils and 数组::比较 https://metacpan.org/pod/Array::Compare,还有更多。还有更复杂的工具也可以用于此目的,例如算法::差异 https://metacpan.org/pod/Algorithm::Diff.