如何从 Perl 中的数组中删除重复值? [英] How do I remove duplicate values from an array in Perl?
本文介绍了如何从 Perl 中的数组中删除重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
对于散列中的每个键,我有多个值.在这里,我打印每个键的值
I have multiple values for each key in the hash. Here, I print the values of each key
print "$var:",join ',',@{$hash{$var}},"\n";
以上打印语句的输出为:
Output of the above print statement is:
ABC:1,2,3,1,4,2,
DEF:9,3,4,5,3,5,
现在,我想删除值中的重复项.所需的输出是,
Now, I want to remove duplicates in the values. The desired output is,
ABC:1,2,3,4
DEF:9,3,4,5
有人可以帮我吗?
谢谢
推荐答案
就个人而言,我喜欢 List::MoreUtils 的 uniq 处理这个.子程序非常简单,可以按原样使用,也可以通过模块使用.
Personally, I like how List::MoreUtils's uniq handles this. The subroutine is quite simple, and can be used as-is, or through the module.
my %seen;
my @dedupe = grep { not $seen{$_}++ } @{$hash{$var}};
模块中的子程序如下所示:
The subroutine from the module looks like this:
sub uniq (@) {
my %seen = ();
grep { not $seen{$_}++ } @_;
}
此代码保留列表的初始顺序.
This code preserves the initial order of the list.
这篇关于如何从 Perl 中的数组中删除重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文