Is there a way to precompile a regex in Perl?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)