in reply to Re: How can I make a string unique (quicker than my approach at least)
in thread How can I make a string unique (quicker than my approach at least)
Hello harangzsolt33,
Maybe somebody ... can explain how this works
Since there is no explicit return, the sub returns the value of its final statement, namely grep !$seen{$_}++, @_;. @_ contains the arguments passed into the sub, and grep filters out those elements that do not make the expression !$seen{$_}++ true. So let’s look at that expression in detail.
%seen is a hash, initially empty. When reference is made to an element that does not yet exist, that element is autovivified. So if $_ is 'x' and the hash has no 'x' key, a hash element is created with key 'x' and value undef.
Now the clever part: postfix ++ increments an item’s value, but the increment is delayed until after the current expression has been evaluated. Further, incrementing undef produces the value 1, because undef is taken to be zero. So if the current value of $_ is not already in the hash %seen, the expression !$seen{$_}++ autovivifies a hash value with key $_ and value undef and applies the logical negation operator ! to the value. Since undef is false by definition, its negation is true and the value of $_ passes through the grep filter into the eventual output of the subroutine.
But the next time $_ has that value, the hash item $seen{$_} exists and has a value of 1 (from the previous application of postfix ++). And since !1 is false, grep filters this item out. In this way, only the first occurrence of any item passes through the filter. So all repeated items are removed from the original list.
Hope that helps,
Athanasius <°(((>< contra mundum | סתם עוד האקר של פרל, |
|
---|