如何在 Perl 中找到一个数组中而不是另一个数组中的元素?

如何在 Perl 中找到一个数组中而不是另一个数组中的元素?

问题描述:

我有两个数组,我想找到一个数组中的元素而不是另一个:

I have two arrays and I want to find elements that are in one array but not another:

例如:

@array1 = ("abc", "cde", "fgh", "ijk", "lmn")
@array2 = ("abc", "fgh", "lmn")

我需要结束:

@array3 = ("cde", "ijk")

将第二个数组的元素放入一个散列中,以便高效检查其中是否包含特定元素,然后过滤第一个数组的元素那些不在第二个数组中的元素:

Put the elements of the second array into a hash, for efficient checking to see whether or not a particular element was in it, then filter the first array for just those elements that were not in the second array:

my %array2_elements;
@array2_elements{ @array2 } = ();
my @array3 = grep ! exists $array2_elements{$_}, @array1;