Perl: while with no conditional

前端 未结 3 1453
不知归路
不知归路 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:56

    This is a special case of the concept of Vacuous Truth. If there is no condition, the statement while the condition is true is itself vacuously true.

    If I am reading this correctly, the relevant piece of code seems to be around line 5853 of op.c in 5.14.1:

    5853     if (expr) {
    5854         scalar(listop);
    5855         o = new_logop(OP_AND, 0, &expr, &listop);
    5856         if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
    5857             op_free(expr);              /* oops, it's a while (0) */
    5858             op_free((OP*)loop);
    5859             return NULL;                /* listop already freed by new_logop */
    5860         }
    5861         if (listop)
    5862             ((LISTOP*)listop)->op_last->op_next =
    5863                 (o == listop ? redo : LINKLIST(o));
    5864     }
    5865     else
    5866         o = listop;
    

    I am assuming with no expr in the condition, we reach o = listop. listop was previously defined as listop = op_append_list(OP_LINESEQ, block, cont);.

提交回复
热议问题