Perl正则表达式中的/o优化或者是一个bug?

4

我在阅读 perldoc perlre 时注意到了这句有点滑稽的话:

o  - pretend to optimize your code, but actually introduce bugs

我搜索了整个文档,但没有找到另一个提到“bugs”的地方。

有人知道使用/o标记会出现什么问题吗?

1个回答

3

我在 perldoc perlfaq6 中找到了这个:

In versions 5.6 and later, Perl won't recompile the regular expression if the variable hasn't changed, so you probably don't need the "/o" option. It doesn't hurt, but it doesn't help either. If you want any version of Perl to compile the regular expression only once even if the variable changes (thus, only using its initial value), you still need the "/o".

You can watch Perl's regular expression engine at work to verify for yourself if Perl is recompiling a regular expression. The "use re 'debug'" pragma (comes with Perl 5.005 and later) shows the details. With Perls before 5.6, you should see "re" reporting that its compiling the regular expression on each iteration. With Perl 5.6 or later, you should only see "re" report that for the first iteration.

    use re 'debug';

    my $regex = 'Perl';
    foreach ( qw(Perl Java Ruby Python) ) {
        print STDERR "-" x 73, "\n";
        print STDERR "Trying $_...\n";
        print STDERR "\t$_ is good!\n" if m/$regex/;
    }
所以,“/o”标志不会对其造成伤害。但是“也没有帮助”。听起来对我来说这不完全是一个错误。

3
有趣的是,使用/o在某些情况下仍然可以使正则表达式更快。程序员使用/o并忘记正则表达式不会被重新编译时,很容易引入错误。 - choroba
1
@choroba,我同意你所说的。 另外,我认为 /o 已经被 qr{} 构造取代了。使用 qr{} 构造还可以更加明显地表明,除非实际上重新分配变量,否则不会对重新使用进行重新插值。 你有什么想法吗? - Miller
2
@Miller:听起来是对的,如果真的是这样就太好了,但是......在基准测试中(例如这里),qr{}比其他替代方案慢得多。 - choroba
2
关于“但这也没有什么帮助”,从技术上讲,它确实有帮助,但不是很大。 - ikegami
这里有一些基准测试,请看这里: https://dev59.com/vnRB5IYBdhLWcg3wr48V#68489725 - Tim Potapov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接