我有两个数组。我需要找出数组的常见元素以及缺少哪些元素以及哪个数组?
我使用下面的代码来查找数组中的公共元素和两个数组中缺少元素的列表。
有人能告诉我如何从每个阵列中找到缺失的元素列表?
例如:
在下面的代码中,我需要打印@arr2
中缺少的元素“ghi”,而@arr1
my @arr1 = ( "abc", "def", "ghi", "jkl" );
my @arr2 = ( "mno", "abc", "jkl", "def" );
my %count = ();
foreach $element ( @arr1, @arr2 ){
$count{$element}++;
}
my @diff = grep { $count{$_} == 1 } keys %count;
my @common = grep { $count{$_} == 2 } keys %count;
答案 0 :(得分:3)
如果您将@arr1
和@arr2
的项目也放在哈希中,您可以这样做:
my @miss1 = grep { $count{$_} == 1 && !exists $arr1{$_} } keys %count;
my @miss2 = grep { $count{$_} == 1 && !exists $arr2{$_} } keys %count;