Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl regex /o optimization or bug?

Tags:

regex

perl

I was reading through perldoc perlre and noticed this somewhat funny line:

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

I searched through the rest of the document, but did not find another reverence to the mentioned "bugs".

Anyone know what are the bugs of using the /o flag?

like image 436
Tim Potapov Avatar asked Sep 12 '25 05:09

Tim Potapov


1 Answers

I found this in 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/;
    }

So "it doesn't hurt" to have the /o flag. But "it doesn't help either".

Sounds to me like it's not exactly a bug.

like image 57
Tim Potapov Avatar answered Sep 15 '25 02:09

Tim Potapov