Reputation: 10453
Is there a way to precompile a regex in Perl? I have one that I use many times in a program and it does not change between uses.
Upvotes: 36
Views: 25563
Reputation: 30831
For literal (static) regexes there's nothing to do -- Perl will only compile them once.
if ($var =~ /foo|bar/) {
# ...
}
For regexes stored in variables you have a couple of options. You can use the qr//
operator to build a regex object:
my $re = qr/foo|bar/;
if ($var =~ $re) {
# ...
}
This is handy if you want to use a regex in multiple places or pass it to subroutines.
If the regex pattern is in a string, you can use the /o
option to promise Perl that it will never change:
my $pattern = 'foo|bar';
if ($var =~ /$pattern/o) {
# ...
}
It's usually better to not do that, though. Perl is smart enough to know that the variable hasn't changed and the regex doesn't need to be recompiled. Specifying /o
is probably a premature micro-optimization. It's also a potential pitfall. If the variable has changed using /o
would cause Perl to use the old regex anyway. That could lead to hard-to-diagnose bugs.
Upvotes: 72
Reputation: 5072
Use the qr// operator (documented in perlop - Perl operators and precedence under Regexp Quote-Like Operators).
my $regex = qr/foo\d/;
$string =~ $regex;
Upvotes: 21
Reputation: 1136
For clarification, you can use a precompiled regex as:
my $re = qr/foo|bar/; # Precompile phase
if ( $string =~ $re ) ... # For direct use
if ( $string =~ /$re/ ) .... # The same as above, but a bit complicated
if ( $string =~ m/something $re other/x ) ... # For use precompiled as a part of a bigger regex
if ( $string =~ s/$re/replacement/ ) ... # For direct use as replace
if ( $string =~ s/some $re other/replacement/x ) ... # For use precompiled as a part of bigger regex, and as replace all at once
It is documented in perlre, but there are no direct examples.
Upvotes: 0