Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
The stupid question is the question not asked
 
PerlMonks  

Answer: Using constants in regexes?

( #427036=categorized answer: print w/ replies, xml ) Need Help??

Q&A > regular expressions > Using constants in regexes? 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.

Comment on Answer: Using constants in regexes?
Select or Download Code
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?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (10)
As of 2014-04-16 12:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (425 votes), past polls