Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling

Answer: Using constants in regexes?

by dclayton (Initiate)
on Feb 01, 2005 at 20:13 UTC ( #427036=categorized answer: print w/replies, xml ) Need Help??

Q&A > regular expressions > Using constants in regexes? - Answer contributed by dclayton

There's a few ways of tackling this problem, depending on your goals. To use a constant as an interpolated value within a regular expression, use the following notation:
if ($string =~ /${\(TEST)}/) {
This has the unfortunate consequence of slowing down your regular expression, since it can't be compiled. Using the qr operator is your best bet. You can use japhy's suggested format:
use constant PATTERN => qr/def/; if ($string =~ PATTERN) { ... }
An alternative is to leave the constant in string format, and compile it just prior to executing the regex:
use constant PATTERN => 'def'; my $regex = qr/${\(PATTERN)}/; #options such as /m can go here. if ($string =~ regex) { ... }
This gives you the added benefit of being able to easily print the regex out for debugging purposes.

Replies are listed 'Best First'.
Re: Answer: Using constants in regexes?
by diotalevi (Canon) on Feb 01, 2005 at 20:48 UTC

    Your statements about the middle example are the only correct thing in your post. In your example /${\(TEST)}/ you state that it can't be compiled. This is false. First time this expression is executed the string form of it is compiled. Since the string form will never change, the compiled expression is retained for the life of the process. You do still incur a runtime hit of evaluating ${\TEST} each time but that is not comparable with the regex compilation cost. That recurring cost can be removed by appending the /o flag which informs the interpreter to never attempt to evaluate the string again. So /${\TEST}/o is perfectly fine and imposes no performance penalty.

    Your last example uses the same logic I just described for the first example. The ${\PATTERN} string is still evaluated every time except this time you never have the option to use the /o parameter.

Log In?

What's my password?
Create A New User
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (2)
As of 2018-05-23 01:56 GMT
Find Nodes?
    Voting Booth?