What characters should I escape in a precompiled Perl regular expression?

I find it difficult to determine which characters should be escaped when using Perl qr {} construct

I am trying to create a multi-line precompiled regular expression for text containing many typically escaped characters (# *.>: []), And also contains another precompiled regular expression. Also, I have to comply as strictly as possible for testing purposes.

my $output = q{# using defaults found in .config
*
*
Options:
  1. opt1
> 2. opt2
choice[1-2?]: };

my $sc = qr{(>|\s)}smx;
my $re = qr{# using defaults found in .config
*
*
Options:
$sc 1. opt1
$sc 2. opt2
choice[1-2?]: }mx;

if ( $output =~ $re ) {
  print "OK!\n";
}
else {
  print "D'oh!\n";
}

Mistake:

Quantifier follows nothing in regex; marked by <-- HERE in m/# using defaults found in .config
* <-- HERE 
*
Options:
(?msx-i:(>|\s)) 1. opt1
(?msx-i:(>|\s)) 2. opt2
choice[1-2?]: / at ./so.pl line 14.

( D'oh). . , , , , - .

+5
3

qr//, , . , *, , * .

, . /M , (^, $)./S , . . /X # .

, , :

my $sc = qr{(>|\s)};

my $re = qr{# using defaults found in \.config
\*
\*
Options:
$sc 1\. opt1
$sc 2\. opt2
choice\[1-2\?]: };

Perl Best Practices, , , . , , , , , .:) , /x. , - , #. , , :

my $sc  = qr{(>|\s)};
my $eol = qr{[\r\n]+};

my $re  = qr{\# \s+ using \s+ defaults \s+ found \s+ in \s+ \.config $eol
\*                    $eol
\*                    $eol
Options:              $eol
$sc \s+ 1\. \s+ opt1   $eol
$sc \s+ 2\. \s+ opt2   $eol
choice\[1-2\?]: \s+
}x;

if ( $output =~ $re ) {
  print "OK!\n";
}
else {
  print "D'oh!\n";
}
+14

, Expect, , , quotemeta, , .

(), unquote ( }) , .[$()|*+?{\

+7

As Brian said, you should avoid the delimiter and regular expression metacharacters. Note that when using qr//x(which you are) you should also avoid whitespace and # (which is a comment marker). You probably don't really want to use it /xhere. If you want to be safe, you can avoid any character other than alphanumeric characters.

+2
source

All Articles