且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 Perl 中的数组中删除重复值?

更新时间:2023-02-20 22:13:47

就个人而言,我喜欢 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.