Perl 正则表达式的“o"修饰符是否仍然提供任何好处? [英] Does the 'o' modifier for Perl regular expressions still provide any benefit?

查看:26
本文介绍了Perl 正则表达式的“o"修饰符是否仍然提供任何好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去认为在 Perl 正则表达式末尾包含o"修饰符是有益的.当前的 Perl 文档 似乎甚至没有列出它,当然没有在 perlre 的修饰符部分.

It used to be considered beneficial to include the 'o' modifier at the end of Perl regular expressions. The current Perl documentation does not even seem to list it, certainly not at the modifiers section of perlre.

现在有什么好处吗?

仍然被接受,出于向后兼容性的原因.

It is still accepted, for reasons of backwards compatibility if nothing else.

正如 J A Faucett 和 brian d foy 所指出的,如果您找到合适的位置(其中一个不是 perlre 文档),o"修饰符仍然被记录在案.perlop 页面中提到了它.它也可以在 perlreref 页面中找到.

As noted by J A Faucett and brian d foy, the 'o' modifier is still documented, if you find the right places to look (one of which is not the perlre documentation). It is mentioned in the perlop pages. It is also found in the perlreref pages.

正如 Alan M 在接受的答案中指出的那样,更好的现代技术通常是使用 qr//(引用的正则表达式)运算符.

As noted by Alan M in the accepted answer, the better modern technique is usually to use the qr// (quoted regex) operator.

推荐答案

/o 已弃用.确保正则表达式只编译一次的最简单方法是使用正则表达式对象,如下所示:

/o is deprecated. The simplest way to make sure a regex is compiled only once is to use use a regex object, like so:

my $reg = qr/foo$bar/;

$bar 的插值在变量 $reg 初始化时完成,并且缓存、编译的正则表达式将在封闭范围内使用.但有时您希望重新编译正则表达式,因为您希望它使用变量的新值.以下是 The Book 中使用的 Friedl 示例:

The interpolation of $bar is done when the variable $reg is initialized, and the cached, compiled regex will be used from then on within the enclosing scope. But sometimes you want the regex to be recompiled, because you want it to use the variable's new value. Here's the example Friedl used in The Book:

sub CheckLogfileForToday()
{
  my $today = (qw<Sun Mon Tue Wed Thu Fri Sat>)[(localtime)[6]];

  my $today_regex = qr/^$today:/i; # compiles once per function call

  while (<LOGFILE>) {
    if ($_ =~ $today_regex) {
      ...
    }
  }
}

在函数作用域内,$today_regex 的值保持不变.但是下次调用该函数时,正则表达式将使用 $today 的新值重新编译.如果他刚刚用过:

Within the scope of the function, the value of $today_regex stays the same. But the next time the function is called, the regex will be recompiled with the new value of $today. If he had just used:

if ($_ =~ m/^$today:/io)

...正则表达式永远不会更新.因此,使用对象形式,您可以在不牺牲灵活性的情况下获得/o 的效率.

...the regex would never be updated. So, with the object form you have the efficiency of /o without sacrificing flexibility.

这篇关于Perl 正则表达式的“o"修饰符是否仍然提供任何好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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