Tuesday, May 14, 2013

Perl : Remove duplicate elements from arrays

How to remove duplicate element from arrays in Perl? Let us see in this article how can duplicates be removed in different ways?

1. Copying distinct elements to new array using grep function:
my @arr=qw(bob alice alice chris bob);
my @arr1;
foreach my $x (@arr){
        push @arr1, $x if !grep{$_ eq $x}@arr1;
}
print "@arr1";
   A loop is run on the array elements. For every element, it is checked to find out whether the element is already present in the new array. If present, it is skipped, else added to the new array.