Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Using constants in regexes?

by dclayton (Initiate)
on Feb 01, 2005 at 20:13 UTC ( [id://427036]=note: print w/replies, xml ) Need Help??


in reply to Using constants in regexes?

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?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://427036]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-18 00:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found