Как удалить повторяющиеся элементы из массива в Perl? - PullRequest
147 голосов
/ 11 августа 2008

У меня есть массив в Perl:

my @my_array = ("one","two","three","two","three");

Как удалить дубликаты из массива?

Ответы [ 11 ]

0 голосов
/ 26 мая 2015

Попробуйте, кажется, для правильной работы функции uniq нужен отсортированный список.

use strict;

# Helper function to remove duplicates in a list.
sub uniq {
  my %seen;
  grep !$seen{$_}++, @_;
}

my @teststrings = ("one", "two", "three", "one");

my @filtered = uniq @teststrings;
print "uniq: @filtered\n";
my @sorted = sort @teststrings;
print "sort: @sorted\n";
my @sortedfiltered = uniq sort @teststrings;
print "uniq sort : @sortedfiltered\n";
...