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

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

问题描述

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

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.

它现在提供任何好处吗?

Does it provide any benefit now?

仍然被接受,因为向后兼容的原因.

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

正如J A Faucett和brian d foy所指出的那样,如果您找到正确的外观,"o"修饰语仍然会被记录在案(其中之一不是perlre文档).在 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.

正如艾伦·M(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.

推荐答案

我确定它仍然受支持,但是已经过时了.如果只想将正则表达式只编译一次,则最好使用正则表达式对象,如下所示:

I'm sure it's still supported, but it's pretty much obsolete. If you want the regex to be compiled only once, you're better off using a regex object, like so:

my $reg = qr/foo$bar/;

$bar的插值是在变量初始化时完成的,因此从此以后,您将始终在封闭范围内使用缓存的,已编译的正则表达式.但是有时您想要重新编译正则表达式,因为您希望它使用变量的新值.这是Frieda在这本书中使用的示例:

The interpolation of $bar is done when the variable is initialized, so you will always be using the cached, compiled regex 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天全站免登陆