Regular Expressions   «Prev 

Perl /o Modifier

The /o modifier only compiles the pattern once. This one is an efficiency thing. Whenever a regular expression is used, it must first be compiled by the regex library. This process effectively turns the expression into internal tokens, which are then run through the regex processing routines. This option tells perl to only compile the pattern once, and then use it as many times as it is called (in a loop for instance).
Beware: if you use this function and you have any variables in your regex, Perl will blindly ignore any changes to those variables after the first time the regex is used.
I have not had occasion to use this modifier, nor have I seen any practical examples of the use of the /o modifier. In order to understand it, I would suggest that you try an experiment in your Perl test bed that uses a variable as part of the pattern, and then changes that variable in between using the pattern. You will find that the pattern does not change even when the variable does. Here is a test you can try:

Perl 6
#!/usr/bin/perl -w
@array = qw ( one two three four );
$pattern = "one";

foreach $x (@array) {
  print "$pattern in $x? ";
  if($x =~ /$pattern/o)
   { print "yes!\n"; }
  else { print "no!\n" }
  $pattern = "three";
  }
If you look at this code, you would expect it to match the first and third items in the array (since the pattern gets changed to "three" when it's in the loop). But if you run it, you will notice that it does not match "three" at all. The reason is the /o modifier.
The first time through the loop, the regex is evaluated (or compiled) and stored internally. The /o modifier tells Perl to go ahead and use that version every time through instead of compiling it again. So later on when $pattern is "three" the regular expression still operates as if it were /one/ and the match fails.
Try this on your system, it will help you to understand it better.

/o operator

The /o operator changes the way in which the regular expression engine compiles the expression. Normally, unless the delimiters are single quotes (which do not interpolate), any variables that are embedded into a regular expression are interpolated at run time, and cause the expression to be recompiled each time. Using the /o operator causes the expression to be compiled only once; however, you must ensure that any variable you are including does not change during the execution of a script otherwise you may end up with extraneous matches.