leszekdubiel has asked for the wisdom of the Perl Monks concerning the following question:

Dear Perl Monks! Please explain why the program doesn't print "Z: passed" but displays "E: failed"?
#!/usr/bin/perl my $a = " -1"; # remove trailing spaces warn "A: pos is ", pos $a; $a =~ /\G */gc; warn "B: pos is ", pos $a; $a =~ /\G(?=-)/gc or die "C: failed"; warn "D: pos is ", pos $a; $a =~ /\G(?=-)/gc or die "E: failed"; print "Z: passed";
output is:
A: pos is at ./l2 line 7. B: pos is 1 at ./l2 line 10. D: pos is 1 at ./l2 line 13. E: failed at ./l2 line 14.
Strange is that "pos $a" is 1, and look ahead for minus sign fails. B: situation is exactly the same as D:, but C: doesn't fail, but E: does...

Replies are listed 'Best First'.
Re: strange behaviour: continue with \G and /gc and look forward
by tybalt89 (Monsignor) on Dec 13, 2019 at 21:12 UTC
    The higher-level loops preserve an additional state between ite +rations: whether the last match was zero-length. To break the loop, the following match after a zero-length match is prohibited to have + a length of zero. This prohibition interacts with backtracking ( +see "Backtracking"), and so the second best match is chosen if the +best match is of zero length.

      Ok thank you very much. Community around perl is great. Actually I've been programming perl for a long time and this bite me for the first time.

      Here is the link:

      https://perldoc.perl.org/perlre.html#Backtracking

      search for phrase " higher-level loops "
Re: strange behaviour: continue with \G and /gc and look forward
by tybalt89 (Monsignor) on Dec 13, 2019 at 21:04 UTC

    regex will not match twice at the same position, it will advance by one on the second attempt.

    It's somewhere in the docs, but I can't find it just now.

      It can match at the same position twice.

      say "[$-[0], $+[0])" while "aaaaa" =~ /a*?/g;
      [0, 0) [0, 1) [1, 1) [1, 2) [2, 2) [2, 3) [3, 3) [3, 4) [4, 4) [4, 5) [5, 5)

        I should have said "regex will not ZERO LENGTH match twice at the same position".

Re: strange behaviour: continue with \G and /gc and look forward
by ikegami (Patriarch) on Dec 14, 2019 at 17:43 UTC

    The following can be used to reset the flag:

    pos($a) = pos($a);
Re: strange behaviour: continue with \G and /gc and look forward
by rsFalse (Chaplain) on Dec 16, 2019 at 10:21 UTC
Re: strange behaviour: continue with \G and /gc and look forward
by rsFalse (Chaplain) on Dec 16, 2019 at 10:30 UTC