I have an array in Perl:
my @my_array = ("one","two","three","two","three");
How do I remove the duplicates from the array?
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 are aiming for universality, you should take a look at the uniq
function. It is included in the core module List::Util
as of Perl v5.26.0 (for older versions, use List::MoreUtils
). This function differs from the above sketch in that it treats undef
as a separate value, different from ''
, and does not issue a warning.