2

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?

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Lou
  • 2,200
  • 2
  • 33
  • 66

1 Answers1

5

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.

simbabque
  • 53,749
  • 8
  • 73
  • 136
  • In addition to speed, pre-compiled patterns also make the code more readable and maintainable, if the same pattern is reused. They are especially handy if the `pattern` is long and/or complex. – Timur Shtatland Aug 20 '20 at 15:24