in reply to Making a subpattern optional with ? causes subpattern match to fail. I am confused as to why.

Regarding your example from the debugger: Your question mark closes the whole construct. After prepending an 'x', the non-capturing parens no longer match at position 0, but since they are optional, they match the empty string - and within that empty string, the first capture is undefined. You can check that by adding the /g modifier to your regex. It should read:

x $foo =~/(?:a=([a-z]+)?)/;

The same would apply to your real pattern, too.

  • Comment on Re: Making a subpattern optional with ? causes subpattern match to fail. I am confused as to why.
  • Download Code

Replies are listed 'Best First'.
Re^2: Making a subpattern optional with ? causes subpattern match to fail. I am confused as to why.
by LanX (Saint) on Aug 16, 2021 at 16:55 UTC
    > they match the empty string - and within that empty string, the first capture is undefined.

    to elaborate further here the proof that it's matching, just at the wrong position

    DB<1> $foo = 'a=b'; DB<2> $foo = 'x' . $foo DB<3> p scalar $foo =~/(?:a=([a-z]+))?/; 1 DB<4> p $1 DB<5> DB<6> p scalar $foo =~/(?:a=([a-z]+))?/g; 1 DB<7> p pos $foo 0 DB<8>

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