in reply to Re: For loop not executing all the values
in thread For loop not executing all the values

Hello GrandFather,

Instead you need a while loop which loops while a condition is true. Actually, you need just a little more work than that. You should loop until the file read returns undef.

Well, according to perlsyn#Compound-Statements, “The while statement executes the block as long as the expression is true.” So far, so good. But if that were the whole story, this:

#! perl use strict; use warnings; print "Contents of \$/: |$/|\n"; print ">$_<\n" while <DATA>; __DATA__ 7 42 0

would print only the first two lines, since the final line — which is not terminated by a newline — is '0' and therefore false. But the final line is printed, because with the <> operator (or its equivalent readline call) the while condition is tested for definedness, not truth. This is documented in perlop#IO/Operators:

In these loop constructs, the assigned value ... is then tested to see whether it is defined. The defined test avoids problems where the line has a string value that would be treated as false by Perl; for example a "" or a "0" with no trailing newline.

All of which is (apparently) undercut by the op’s assertion, below, that adding an explicit test for definedness solved his problem. I don’t know how to explain that. An early version of Perl? A strange value for $/? I do know that perlop#IO/Operators says the following are equivalent:

while (defined($_ = <STDIN>)) { print; } while ($_ = <STDIN>) { print; } while (<STDIN>) { print; }

and immediately goes on to imply that explicit assignment to a lexical variable “behaves similarly” to implicit assignment to the default variable, $_.

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Replies are listed 'Best First'.
Re^3: For loop not executing all the values
by GrandFather (Saint) on Sep 02, 2015 at 00:35 UTC

    Hmm, that looks like cargo culting on my part. I had the impression that in the past the explicit assignment broke the special handling for <> in while loop expressions. A quick look through the Perl documentation doesn't support that impression for any version of Perl I've ever used so there is a bunch of code I can tidy up!

    I'll leave my post above as is to avoid confusion for future readers.

    Premature optimization is the root of all job security