Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: while with no conditional

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?

like image 523
Eugene Yarmash Avatar asked Apr 26 '12 12:04

Eugene Yarmash


People also ask

What does while do in Perl?

A while loop statement in Perl programming language repeatedly executes a target statement as long as a given condition is true.

How do you write a while loop in Perl?

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.

Do While statements Perl?

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.

How do you skip a loop in Perl?

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.


1 Answers

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

like image 124
TLP Avatar answered Sep 24 '22 00:09

TLP