4

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?

Tim Potapov
  • 431
  • 2
  • 12

1 Answers1

3

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.

sticky bit
  • 36,626
  • 12
  • 31
  • 42
Tim Potapov
  • 431
  • 2
  • 12
  • 3
    Interestingly, using `/o` still makes regexes faster in some cases. The bugs are easily introduced by the programmer using `/o` and forgetting that the regex won't be recompiled. – choroba Jul 20 '21 at 11:44
  • 1
    @choroba Agreed on what you said. As a secondary thought, I would argue that ```/o``` was made obsolete by the ```qr{}``` construct. The ```qr{}``` construct also makes it a lot more obvious that the re won't be reinterpolated upon repeated usages unless one actually reassigns to the variable. thoughts? – Miller Jul 20 '21 at 16:38
  • 2
    @Miller: Sounds right and would be nice if it were true, but... in benchmarks (e.g. [here](https://www.perlmonks.org/?node_id=1205956)) `qr{}` is much slower than the alternatives. – choroba Jul 20 '21 at 20:41
  • 2
    Re "*but it doesn't help either*", Technically, it does, but not much. – ikegami Jul 21 '21 at 00:26
  • Take a look here for some benchmarks: https://stackoverflow.com/questions/550258/does-the-o-modifier-for-perl-regular-expressions-still-provide-any-benefit/68489725#68489725 – Tim Potapov Jul 22 '21 at 18:35