What is the difference between qr/ and m/ in Perl?

1k views Asked by At

From Perldoc:

qr/STRING/msixpodualn

This operator quotes (and possibly compiles) its STRING as a regular expression. STRING is interpolated the same way as PATTERN in m/PATTERN/.

m/PATTERN/msixpodualngc
/PATTERN/msixpodualngc

Searches a string for a pattern match, and in scalar context returns true if it succeeds, false if it fails. If no string is specified via the =~ or !~ operator, the $_ string is searched. (The string specified with =~ need not be an lvalue--it may be the result of an expression evaluation, but remember the =~ binds rather tightly.) See also perlre.

Options are as described in qr// above

I'm sure I'm missing something obvious, but it's not clear at all to me how these options are different - they seem basically synonymous. When would you use qr// instead of m//, or vice versa?

1

There are 1 answers

1
simbabque On

The m// operator is for matching, whereas qr// produces a pattern (as a string) that you can stick in a variable and store for later. It's a quoted regular expression pattern.

Pre-compiling the this way is useful for optimising your run-time cost, e.g. if you are using a fixed pattern in a loop with millions of iterations, or you want to pass patterns around between function calls or use them in a dispatch table.

# match now
if ( $foo =~ m/pattern/ ) { ... }

# compile and use later
my $pattern = qr/pattern/i;
print $pattern;                      # (?^ui:pattern)

if ($foo =~ m/$pattern/) { ... }

The structure of the string (in this example, (?^ui:pattern)) is explained in perlre. Basically (?:) creates a sub-pattern with built-in flags, and the ^ says which flags not to have. You can use this inside other patterns too, to turn on and off case-insensitivity for parts of your pattern for example.