Regex $1 into variable interferes with another variable

后端 未结 1 1541
猫巷女王i
猫巷女王i 2021-01-16 10:39

I have been struggling with a section of my code for a while now and can\'t figure it out. Seems to have something to do with how $1 is handled but I cannot find anything re

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-16 11:11

    It's because you used if (//g) instead of if (//).

    • //g in scalar context sets pos($_)[1] to where the match left off, or unsets pos($_)[1] if the match was unsuccessful[2].
    • //g in scalar context starts matching at position pos($_)[1].

    For example,

    $_ = "ab";
    say /(.)/g ? $1 : "no match";  # a
    say /(.)/g ? $1 : "no match";  # b
    say /(.)/g ? $1 : "no match";  # no match
    say /(.)/g ? $1 : "no match";  # a
    

    This allows the following to iterate through the matches:

    while (/(.)/g) {
       say $1;
    }
    

    Don't use if (//g)[3]!


    1. $_ is being used to represent the variable being matched against.
    2. Unless /c is also used.
    3. Unless you're unrolling a while (//g), or unless you're using if (//gc) to tokenize.

    0 讨论(0)
提交回复
热议问题