Is there a way to precompile a regex in Perl?

柔情痞子 提交于 2019-12-17 18:22:11

问题


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.


回答1:


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.




回答2:


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

my $regex = qr/foo\d/;
$string =~ $regex;



回答3:


for clarification, you can user 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 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, and as replace all at once

It is documented in perlre but there are no direct examples.



来源:https://stackoverflow.com/questions/952998/is-there-a-way-to-precompile-a-regex-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!