Is Perl's flip-flop operator bugged? It has global state, how can I reset it?

前端 未结 6 1246
旧时难觅i
旧时难觅i 2020-12-13 18:36

I\'m dismayed. OK, so this was probably the most fun Perl bug I\'ve ever found. Even today I\'m learning new stuff about Perl. Essentially,

6条回答
  •  时光取名叫无心
    2020-12-13 19:34

    The "range operator" .. is documented in perlop under "Range Operators". Looking through the doucmentation, it appears that there isn't any way to reset the state of the .. operator. Each instance of the .. operator keeps its own state, which means there isn't any way to refer to the state of any particular .. operator.

    It looks like it's designed for very small scripts such as:

    if (101 .. 200) { print; }
    

    The documentation states that this is short for

    if ($. == 101 .. $. == 200) { print; }
    

    Somehow the use of $. is implicit there (toolic points out in a comment that that's documented too). The idea seems to be that this loop runs once (until $. == 200) in a given instance of the Perl interpreter, and therefore you don't need to worry about resetting the state of the .. flip-flop.

    This operator doesn't seem too useful in a more general reusable context, for the reasons you've identified.

提交回复
热议问题