如何在 Perl 中找到一个数组中而不是另一个数组中的元素? [英] How can I find elements that are in one array but not another in Perl?

查看:27
本文介绍了如何在 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;

这篇关于如何在 Perl 中找到一个数组中而不是另一个数组中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆