Wednesday 21 September 2011

How to remove repeated entries from a Perl array



How to remove repeated entries from a Perl array

Simply assign each elements of array to a key of hash variable.
And extract the keys.

Sample code is as bellow.

#--------------------------------
my @array = qw(3 1 2 3  5 4 2 66 44 55 4 5 6 7 8 9);
print join " ", @array, "\n";
my @array1 = uniq(@array);
print join " ", @array1, "\n";

sub uniq {
    return keys %{{ map { $_ => 1 } @_ }};
}

1 comment: