Perl: while with no conditional

前端 未结 3 1455
不知归路
不知归路 2021-02-01 13:16

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:

3条回答
  •  面向向阳花
    2021-02-01 14:08

    $ 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($_ = )) {
        ();
    }
    -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.

提交回复
热议问题