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.) |