From: PerlFAQ Server on
This is an excerpt from the latest version perlfaq6.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at .


6.10: What is "/o" really for?

(contributed by brian d foy)

The "/o" option for regular expressions (documented in perlop and
perlreref) tells Perl to compile the regular expression only once. This
is only useful when the pattern contains a variable. Perls 5.6 and later
handle this automatically if the pattern does not change.

Since the match operator "m//", the substitution operator "s///", and
the regular expression quoting operator "qr//" are double-quotish
constructs, you can interpolate variables into the pattern. See the
answer to "How can I quote a variable to use in a regex?" for more

This example takes a regular expression from the argument list and
prints the lines of input that match it:

my $pattern = shift @ARGV;

while( <> ) {
print if m/$pattern/;

Versions of Perl prior to 5.6 would recompile the regular expression for
each iteration, even if $pattern had not changed. The "/o" would prevent
this by telling Perl to compile the pattern the first time, then reuse
that for subsequent iterations:

my $pattern = shift @ARGV;

while( <> ) {
print if m/$pattern/o; # useful for Perl < 5.6

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

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


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in