如何在perl中找到重复的数组值
可能重复:如何在perl中找到重复的数组值,perl,Perl,可能重复: 如何在数组中查找重复值 这是我的阵列: @arr - ("one","two","one","three","two"); 输出将是: one two 代码: while(){ 咀嚼; @arr=拆分(/\ \124;/,$); 推送(@arr1,$arr[4]。“\n”); } 使用散列的替代方法: my @arr = ("one", "two", "one", "three", "two"); my %arr_counts; for (@arr) { $arr_counts
如何在数组中查找重复值 这是我的阵列:
@arr - ("one","two","one","three","two");
输出将是:
one
two
代码:
while(){
咀嚼;
@arr=拆分(/\ \124;/,$);
推送(@arr1,$arr[4]。“\n”);
}
使用散列的替代方法:
my @arr = ("one", "two", "one", "three", "two");
my %arr_counts;
for (@arr) { $arr_counts{$_}++ };
my @dupes = grep { $arr_counts{$_} > 1 } keys %arr_counts;
请注意,散列并不维护排序顺序。它不是随机的,因此,如果您使用相同的列表运行,您将获得相同的结果,但在实践中顺序会发生变化。单次解决方案:
my %seen = ();
@dup = map { 1==$seen{$_}++ ? $_ : () } @list;
为什么“三”不应该出现在输出中?
my @arr = ("one", "two", "one", "three", "two");
my %arr_counts;
for (@arr) { $arr_counts{$_}++ };
my @dupes = grep { $arr_counts{$_} > 1 } keys %arr_counts;
my %seen = ();
@dup = map { 1==$seen{$_}++ ? $_ : () } @list;