给定一个元素数组,如何找到仅在该数组中出现一次的元素:
my @array = qw(18 1 18 3 18 1 1 2 3 3);
Run Code Online (Sandbox Code Playgroud)
结果应该是:2
这是perlfaq5的变体- 如何从列表或数组中删除重复的元素?
只需使用哈希计算元素,然后打印只看过一次的元素.
use strict;
use warnings;
my @array = qw(18 1 18 3 18 1 1 2 3 3);
my @nondup = do {
my %count;
$count{$_}++ for @array;
grep {$count{$_} == 1} keys %count;
};
print "@nondup\n";
Run Code Online (Sandbox Code Playgroud)
输出:
2
Run Code Online (Sandbox Code Playgroud)