in reply to Explain the code
The grep function takes 2 parameters. The first is an expression to be executed for each element in the list. The second is the list to iterate over.my @result = grep { !$seen{$_}++ } @a;
grep then foreachs through the list @a and for every element it sets $_ = that element.
Then it evaluates the expression !$seen{$_}++. This takes the current entry and does one of 2 things:1) if there is no entry in the %seen hash then it puts a zero in there. So the $seen{$_} evaluates to (0)false. Add the ! negation operator and you can see that the expression passed to grep only evaluates to true for values on their first encounter. Furthermore, the ++ is post-increment so it happens after expression returns it's value.
2) if we have seen it, increment the entry. This causes the expression to be simplified down to the negation of a positive number, which is false.grep will just will just run through it's list checking the expression against each element. The elements that evaluate to true are returned as @result.
Nice use of grep. You should see some of my legacy code for dedupping a list!!
|
|---|