Tielman Koekemoer (TNE) <[EMAIL PROTECTED]> asked:
> I've just come back to your post above (30/05/05) and I've 
> tried to get the internal workings of the code to agree with 
> my brain. Please help!
> 
> > perl -e'print sort grep !$seen{$_}++, <>' FILENAME
> 
> Initially I thought you were creating a hashref(?) key with 
> every line of input, if unique. But I cannot access the keys 
> using the hashref
> (below) so there is something else at work here.
> 
> for $key_v (keys %{$seen}) {
>         print "$key_v\n";
> }
>
> This returns nothing when used with the above code in a 
> script (code posted at request). Sorry in advance if I've 
> made newbie mistake but please explain how !$seen{$_}++ knows 
> what was used before.

He's using just a hash, namely %seen. What he's doing is
reading all the files on the command line (or standard input
if there are no filename arguments) in list context, i.e.
he turns them into a large list of lines. This list is then
"filtered" by the grep command. This will return a subset of
the argument list - namely those items for which the grep
expression is true. That expression is "!$seen{$_}++".
$_ will be on of the lines. The first time a unique line
is evaluated in this expression, $seen{$_} does not exist
and the value is undefined. The ! operator forces this into
a boolean false and returns boolean true, i.e. the line will
be part of the result set. the post-increment ++ operator
will then create a hash key with the line as key and assign
it (undef)+1 = 1 as a value. So when the line is encountered
again, it will evaluate to a positive number, which will be
negated to false by the ! operator, which in turn means that
the line will not be put into the result set twice.
 
> PS Will the Perl Cookbook have examples to common tools such as this?
> What does everyone think of the book - very helpful?

It has lots of useful code snippets, and they are commented
well enough to follow with a basic grasp of Perl. I would
not want to miss it in my library. It also used to be part
of a Book/CD set called the Perl Bookshelf. AFAIK it's out
of print but you might be able to pick it up at a used book
store (or onlinle at ABEbooks) cheaply.

Alternatively, if you want to learn about Perl style, check
out Joseph N. Hall's Effective Perl Programming.

HTH,
Thomas

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to