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

Why global regex doesnot work as tested on debug interactive:
$str='kklmn; $str=~ s/(?=(kkl))(?(1)\g1|mn)/***/g; print "$str\n"; ***mn

only first is processed, what is the point of failure here ?
Please help and thanks before

Replies are listed 'Best First'.
Re: Doing by global regex does not work as on debug
by AnomalousMonk (Archbishop) on Dec 05, 2021 at 02:46 UTC
    ... what is the point of failure ...

    There is no failure. As LanX pointed out, the regex is doing exactly what it's been told to do.

    Win8 Strawberry 5.30.3.1 (64) Sat 12/04/2021 21:26:27 C:\@Work\Perl\monks >perl -Mstrict -Mwarnings my $str='kklmn'; # +--------------- if you look ahead to kkl # | # | +---+-------- while also capturing it to capture group 1 # | | | (match point is not advanced) # | | | # | | | +-------- and then if capture 1 captured anything # | | | | # | | | | +----- match with what was captured to $1 # | | | | | # | | | | | +-- else match with mn # | | | | | | # | | | | | | +------- and substitute this # | | | | | | | # v v---v v v v v $str=~ s/(?=(kkl))(?(1)\g1|mn)/***/g; print "'$str' \n"; ^Z '***mn'

    Update (many days later):

    ... what is the point of failure ...
    The point of failure is to learn.


    Give a man a fish:  <%-{-{-{-<

Re: Doing by global regex does not work as on debug
by LanX (Saint) on Dec 04, 2021 at 23:22 UTC

    That's a tautological mess.°

    You've just invented a super complicated

    $str =~ s/kkl/***/g;

    Please try to explain what you expect in an SSCCE

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

    °) actually it's legal code, a conditional regex which is only true after the group inside lookahead assertion matched, but can't ever be false because the former assertion skips those positions already 🤷🏻‍♂️

Re: Doing by global regex does not work as on debug
by Anonymous Monk on Dec 05, 2021 at 18:08 UTC

    Note that this was also posted in p5p, where it was noted that the example as given does not compile.

      > the example as given does not compile.

      there is a quote missing, yes!

      ... apart from this it "works".

      DB<324> $str='kklmn' # end quote added DB<325> $str=~ s/(?=(kkl))(?(1)\g1|mn)/***/g DB<326> print $str ***mn DB<327>

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery