I'm a perl beginner. I try to filter duplicate entries. I found something online that magically works for me but I don't quite understand it. Could someone please explain it in detail for me?
my %seen;
grep !$seen{$_}++, @_;
I'm a perl beginner. I try to filter duplicate entries. I found something online that magically works for me but I don't quite understand it. Could someone please explain it in detail for me?
my %seen;
grep !$seen{$_}++, @_;
It might help to see this written out in more detail.
# Hash to keep track of what you've seen
my %seen;
# Array to store the first occurrence of each value
@values;
foreach my $x (@_) {
# If we haven't seen this value already
if (!$seen{$x}) {
# Push this value onto @values
push @values, $x;
}
# Increment the value in %seen to say we've seen this value
$seen{$x}++;
}
# At the end, the unique values are in @values
%seen
is a hash variable.
@_
is a array and it hold all your input parameters
The first time the loop sees an element, that element has no key in %seen. The next time the loop sees that same element, its key exists in the hash and the value for that key is true then it skips the element and go to next element.
you can find more details : What are the differences between $, @, % in Perl variable declaration? and here