Perl: while with no conditional

Eugene Yarmash picture Eugene Yarmash · Apr 26, 2012 · Viewed 13.7k times · Source

According to the doc, the while statement executes the block as long as the expression is true. I wonder why it becomes an infinite loop with an empty expression:

while () { # infinite loop
 ...
}

Is it just inaccuracy in the doc?

Answer

TLP picture TLP · Apr 26, 2012
$ perl -MO=Deparse -e 'while () { }'
while (1) {
    ();
}
-e syntax OK

It seems that while () {} and while (1) {} are equivalent. Also note that empty parens* are inserted in the empty block.

Another example of pre-defined compiler behaviour:

$ perl -MO=Deparse -e 'while (<>) { }'
while (defined($_ = <ARGV>)) {
    ();
}
-e syntax OK

I would say that this is just the docs not reporting a special case.

* — To be precise, the stub opcode is inserted. It does nothing, but serves a goto target for the enterloop opcode. There's no real reason to note this. Deparse denotes this stub op using empty parens, since parens don't generate code.