Perl: while with no conditional

前端 未结 3 1452
不知归路
不知归路 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 13:48

    This is a special case. An empty condition expression defaults to just true, which means "loop forever, or until a break. In C (and perl) the idiom

    for(;;) {
       // Neverending fun
    }
    

    has the same effect for the same reason.

    There doesn't appear to be any mention of this in the official perl docs, and yet there is a special rule in the parser for it. Perhaps it's because nobody uses it :)

    The for(;;) idiom is less uncommon though.

提交回复
热议问题