How do I remove duplicate items from an array in Perl?

David picture David · Aug 11, 2008 · Viewed 218k times · Source

I have an array in Perl:

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

How do I remove the duplicates from the array?

Answer

Greg Hewgill picture Greg Hewgill · Aug 11, 2008

You can do something like this as demonstrated in perlfaq4:

sub uniq {
    my %seen;
    grep !$seen{$_}++, @_;
}

my @array = qw(one two three two three);
my @filtered = uniq(@array);

print "@filtered\n";

Outputs:

one two three

If you want to use a module, try the uniq function from List::MoreUtils