- publishing free software manuals
Perl Language Reference Manual
by Larry Wall and others
Paperback (6"x9"), 724 pages
ISBN 9781906966027
RRP £29.95 ($39.95)

Sales of this book support The Perl Foundation! Get a printed copy>>>

4.8 For Loops

Perl's C-style for loop works like the corresponding while loop; that means that this:

for ($i = 1; $i < 10; $i++) {

is the same as this:

$i = 1;
while ($i < 10) {
} continue {

There is one minor difference: if variables are declared with my in the initialization section of the for, the lexical scope of those variables is exactly the for loop (the body of the loop and the control sections).

Besides the normal array index looping, for can lend itself to many other interesting applications. Here's one that avoids the problem you get into if you explicitly test for end-of-file on an interactive file descriptor causing your program to appear to hang.

$on_a_tty = -t STDIN && -t STDOUT;
sub prompt { print "yes? " if $on_a_tty }
for ( prompt(); <STDIN>; prompt() ) {
    # do something

Using readline (or the operator form, <EXPR>) as the conditional of a for loop is shorthand for the following. This behaviour is the same as a while loop conditional.

for ( prompt(); defined( $_ = <STDIN> ); prompt() ) {
    # do something
ISBN 9781906966027Perl Language Reference ManualSee the print edition