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

To the most erudite Perl savants,
I have the following regex
s/^ \s* (?<term>  \b\w+\b|(?:'.+?')|(?:".+?") )//isx
Because I will use part of that regex in another piece of code, I am trying to simplify things by having the variable $TERMSDEF hold this text:
\b\w+\b|(?:'.+?')|(?:".+?")
and then interpolating it into the regex like so:
s/^ \s* (?<term> $TERMSDEF)//isx
But now the code that matched the old regex doesn't match the new regex. What am I doing wrong?

Replies are listed 'Best First'.
Re: Regex won't match.
by Sue D. Nymme (Monk) on Sep 20, 2009 at 22:52 UTC

    Probably what you're doing wrong is assigning the string to the variable wrong. But since you didn't show how you did that, it's just a guess.

    Usually, what you want to do is this:

    $TERMSDEF = qr/\b\w+\b|(?:'.+?')|(?:".+?")/;

    That will preserve all the regex semantics, keep your code readable, cure cancer, etc.

      To be equivalent, it should be:

      $TERMSDEF = qr/\b\w+\b|(?:'.+?')|(?:".+?")/isx;

      Mind you, the "i" and "x" are useless here, but the "s" is necessary.

      Excellent! It works now. Thank you.
Re: Regex won't match.
by ikegami (Patriarch) on Sep 21, 2009 at 02:20 UTC

    What am I doing wrong?

    Hard to tell, since you didn't show us what you did. But I bet if you printed $TERMSDEF, you would have noticed it didn't contain what you'd hope it would contain because you didn't escape your slashes properly.