in reply to Regular Expression Constructs ?<= and ?=

First, do you realize
(??{ print $^N })
is causing the regexp to try to match "1", the return value of print? You should probably use something that's guaranteed not to match like
(??{ print("$^N\n"); '(?!)' })
or something that's guaranteed to match like
(??{ print("$^N\n"); '(?=)' })
(depending on your intention) instead of relying on the return value of print and the presence/absence of the return value of print in the string to match.

You use /g, so I assume you'll call the regexp more than once in a scalar context, or in a list context.

So compare

local $_ = 'aaaaabaaaaab'; 1 while / ( (?<=a) (a) (?=[ab]) ) (??{ print $^N; '(?=)' }) /gx; print("\n");

with

local $_ = 'aaaaabaaaaab'; 1 while / a (a) [ab] (??{ print $^N; '(?=)' }) /gx; print("\n");

The first outputs "aaaaaaaa", which the second outputs "aaaa".

(?=...) is useful when followed by something which isn't zero-width, when /g is used and when used in substititutions.

(?<=...) is useful when /g is used and when used in substititutions.

Replies are listed 'Best First'.
Re^2: Regular Expression Constructs ?<= and ?=
by BrowserUk (Patriarch) on Jan 12, 2006 at 03:08 UTC
    First, do you realize (??{ print $^N }) is causing the regexp to try to match "1", the return value of print? You should probably use something that's guaranteed not to match like (??{ print("$^N\n"); '(?!)' })or something that's guaranteed to match like (??{ print("$^N\n"); '(?=)' })

    Or if you are only using the contents of the code block for it's side effects, use (?{ ... }) which always succeeds and otherwise has no effect upon the matching process. From perlre

    This zero-width assertion evaluates any embedded Perl code. It always succeeds, and its code is not interpolated.

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

      Or if you *do* want your code's evaluation to affect the regex's match, use the conditional expression (?(...)...|...).

      (?(?{ YOUR CODE HERE }) TRUE | FALSE )

      ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊