qr operator - create a regular expression reference
You can create regular expression reference with the qr operator . You can use the qr operator to save a regular expression as a reference in a variable. You can also save regular expression options. Regular expressions are compiled, so they work faster when doing repeated pattern matching.
# Regular expression reference my $regex = qr/\d+/sm;
When performing pattern matching, you can put it in // or use it as it is. I think it's a little easier to see if you put it in //.
# Used in // if ($str =~ /$regex/) { ... } # Use as it is if ($str =~ $regex) { ... }
What is a reference?
The reference is explained in detail in the following article.
- Let's master how to use reference
Example
This is an example using a regular expression reference.
use strict; use warnings; # You can use qr // to save the options as well. # (The g option cannot be specified.) my $word = "ababab"; my $regex = qr/A/i; my $replace = 'c'; $word =~ s/$regex/$replace/g; print "\$word = $word\n";
Output.
$word = cbcbcb