in reply to What does !$saw{$_}++ means
With no change to the idiom, I'd write that as,
%saw is a hash, initialized empty in the my declaration. I changed that to keep from eliminating and then automatically reproducing (autovivifying) a global %saw.my %saw; my @out = grep { ! $saw{$_}++ } @in;
The expression $saw{$_}++ adds one to the value associated with the key that is $_'s value. It returns the value $saw{$_} had before the addition. $_ is a variable grep sets in turn to each element of @in. "!" is logical "not", so the boolean value $saw{$_} had is inverted. That means grep only sees true when the hash hadn't seen the key yet. Thus, grep only passes along the first instance it sees of each element in @in.
This is an idiom. It seems complicated at first, but will soon be second nature to you. Sometimes it is written to increment $saw{$_} in a loop over @in, and then set @out to keys(%saw), but that doesn't preserve the order of the elements. Yours does.
After Compline,
Zaxo
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: What does !$saw{$_}++ means
by Anonymous Monk on Jan 26, 2005 at 09:56 UTC | |
Re^2: What does !$saw{$_}++ means
by blazar (Canon) on Jan 26, 2005 at 09:06 UTC |