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?
A while loop statement in Perl programming language repeatedly executes a target statement as long as a given condition is true.
A while loop in Perl generally takes an expression in parenthesis. If the expression is True then the code within the body of while loop is executed. A while loop is used when we don't know the number of times we want the loop to be executed however we know the termination condition of the loop.
In practice, you use the do... while loop statement when you want the loop executes at least one before the condition is checked. When you enter the by string in the command line, the condition in the do while statement becomes false that terminates the loop.
The Perl next statement is used inside a loop to start the next iteration and skip all code below it. In practice, you often use the next statement in conjunction with the if statement to specify a condition to start the next iteration. Typically, you use the next statement in the while and for loop statement.
$ 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With