有没有办法在 Perl 中预编译正则表达式? [英] Is there a way to precompile a regex in Perl?

查看:33
本文介绍了有没有办法在 Perl 中预编译正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Perl 中预编译正则表达式?我有一个我在一个程序中多次使用它并且它在使用之间不会改变.

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.

推荐答案

对于文字(静态)正则表达式没有什么可做的 -- Perl 只会编译它们一次.

For literal (static) regexes there's nothing to do -- Perl will only compile them once.

if ($var =~ /foo|bar/) {
    # ...
}

对于存储在变量中的正则表达式,您有几个选择.您可以使用 qr//用于构建正则表达式对象的运算符:

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.

如果正则表达式模式在字符串中,您可以使用 /o 选项向 Perl 承诺它永远不会改变:

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) {
    # ...
}

不过,通常最好不要这样做.Perl 足够聪明,知道变量没有改变,并且不需要重新编译正则表达式.指定 /o 可能是一个过早的微优化.这也是一个潜在的陷阱.如果变量 has 使用 /o 更改,则无论如何都会导致 Perl 使用旧的正则表达式.这可能会导致难以诊断的错误.

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.

这篇关于有没有办法在 Perl 中预编译正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆