Does the ‘o’ modifier for Perl regular expressions still provide any benefit?

/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/;

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) {

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)

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

Leave a Comment