To remove duplicates from an array in Perl, you can use the `uniq` function from the List::MoreUtils module or loop through the array to filter out duplicates manually.
In this example,
use List::MoreUtils qw(uniq);
my @numbers = (1, 2, 2, 3, 4, 4, 5);
my @unique_numbers = uniq(@numbers);
print "Array without duplicates: @unique_numbers\n";
Array without duplicates: 1 2 3 4 5
In this example,
my @colors = ("red", "green", "blue", "green", "yellow", "blue");
my %seen;
my @unique_colors;
foreach my $color (@colors) {
unless ($seen{$color}) {
push @unique_colors, $color;
$seen{$color} = 1;
}
}
print "Array without duplicates: @unique_colors\n";
Array without duplicates: red green blue yellow
In this tutorial, we learned How to Remove Duplicates in an Array in Perl language with well detailed examples.