views:

633

answers:

2

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.

+7  A: 

Simple: Check the qr// operator (documented in the perlop under Regexp Quote-Like Operators).

my $regex = qr/foo\d/;
$string =~ $regex;
tsee
+15  A: 

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.

Michael Carman
These are true; however, qr// has been supported for many years now (it's existed since 5.005, and I think there's been no issues with it since 5.8)
ephemient
@ephemient Well, 5.10 has a nasty memory leak associated with qr// (and compiling regexes in general), but that has been fixed. If you are using 5.10, you can check to see if you have the memory leak by saying perl -e 'qr// while 1'. I know that the OS X version of ActiveState Perl 5.10 is still broken.
Chas. Owens