Do you know where your variables are? | |
PerlMonks |
Re: What does !$saw{$_}++ meansby Corion (Patriarch) |
on Jan 26, 2005 at 08:39 UTC ( [id://425141]=note: print w/replies, xml ) | Need Help?? |
Let's split it up a bit: You have a hash, %saw. Individual elements of a hash are accessed via $hash{key}. If you append the postfix ++ operator to it, it looks like $saw{key}++, which increments the hash element by one. Now, what does that do? The grep iterates over the whole array @in, sets $_ to each element and then executes the code, in our case the expression !$saw{$_}++. If the expression returns a true value, grep keeps the array element in its result, otherwise it's discarded. Now, when a key in %saw does not already exists, the code sets $saw{key} to 1 (incrementing by one from undef), and then returns the negation of the previous hash value (undef is false, so it returns true). So, if the hash key did not yet exist in the hash, the array element is put into @out. The other case is that the hash key already exists in the hash. Then $saw{$_} returns a number greater than zero, which is interpreted as true, and the negation of that is false, so the (duplicate) array element in @in is discarded. This method is a nice and easy way (once you understand it) to get a unique list of elements in an array while retaining the order. There are other methods, like using the keys of %saw:
This code puts the same elements into @out, but you lose the order. I don't remember if it was quicker, but there also is the non-looped version:
In Section
Seekers of Perl Wisdom
|
|