The fastest and most efficient in this case is:
s/foo/bar/i;
The difference between qr//, using /o, and using no flag is
the time of binding variables in your pattern to the RE.
If (as in this case) the pattern doesn't involve any
variables, perl will recognize that at compile time and you
should leave it to the interpreter. However if your
pattern involves a variable, there are three basic
possibilities.
- The safest assumption is that your variable
may change at any time, and your pattern will need to be
recompiled before each use. That is what you get by
default.
- The fastest but most dangerous assumption is that
your variable is a constant that never will change in the
lifetime of your program. That is what /o is for.
- In between those two extremes you have cases where the
programmer knows that a pattern will be used repeatedly but
the variable it depends on may change. The qr// construct
(which is explained in your local documentation, try
perldoc perlop) is for this case. Here when you
call qr// you are telling Perl exactly when to compile the
pattern. I typically would do it in functions where I
will be matching a pattern many times. I want the speedup,
but I don't want to risk having my function work incorrectly
if it is called twice.
In older Perl's (say Camel 2 vintage) there wasn't a
qr// operator (introduced in 5.004 IIRC). To get a
similar effect people used to use
eval to produce an
anonymous subroutine that would do the match and had a
hard-coded pattern. (By showing a friend how to do this
I sped his data-cleaning-and-loading program up by 40%.)
I mention this as a historical curiousity only, today you
would just use qr// for this problem.
Note
This is my 1000'th post. I had thought about issuing some
sort of general thank-you, but then I decided that the
best kind of thank-you for finding both Perl and this site
enjoyable is giving another explanation. If I didn't
enjoy it, I wouldn't be here. :-)