in reply to Re: Reading a pipe
in thread Reading a pipe

In other words,
while (my $line = <STDIN>) { &do_something_with($line); }

Replies are listed 'Best First'.
Re: Re: Re: Reading a pipe
by chipmunk (Parson) on Apr 03, 2001 at 08:20 UTC
    There appears to be a lot of confusion in this thread. I hope this node will help to clear things up.

    In older versions of Perl, this code:

    while (my $line = <STDIN>) { &do_something_with($line); }
    would exit the while loop early under one condition; when the last line of input is '0', with no trailing newline. The solution to this problem was to add a defined() test around the assignment:
    while (defined(my $line = <STDIN>)) { &do_something_with($line); }
    However, as of perl5.005, the defined() test is performed automatically! Thus, the above two snippets of code would be equivalent.

    Here's what the documentation from perl5.6.0 has to say, in a snippet from perlop :

    The following lines are equivalent: while (defined($_ = <STDIN>)) { print; } while ($_ = <STDIN>) { print; } while (<STDIN>) { print; } for (;<STDIN>;) { print; } print while defined($_ = <STDIN>); print while ($_ = <STDIN>); print while <STDIN>; This also behaves similarly, but avoids $_ : while (my $line = <STDIN>) { print $line } In these loop constructs, the assigned value (whether assignment is automatic or explicit) is then tested to see whether it is defined. The defined test avoids problems where line has a string value that would be treated as false by Perl, for example a "" or a "0" with no trailing newline. If you really mean for such value +s to terminate the loop, they should be tested for explicitly: while (($_ = <STDIN>) ne '0') { ... } while (<STDIN>) { last unless $_; ... }
    (A similar explanation can be found in the 5.005 docs, but I found this one from 5.6.0 to be clearer.)
Re: Re: Re: Reading a pipe
by Anonymous Monk on Apr 02, 2001 at 22:53 UTC
    If the line ever begins with a 0, my $line = <STDIN> will evaluate to false and the loop will end. You can use a defined() around it or
    while(<STDIN>) { #or just while(<>) &do_something_with($_); }
      If the line ever begins with a 0, my $line = <STDIN> will evaluate to false and the loop will end.

      This is false. Try it.
        You are correct, it is false with a current version of perl. I believe it is true with older versions, but I don't know how old.