Orange Peel Orange Peel - 28 days ago 4x
Perl Question

Perl match regex variable \Q

I'm trying to match a regex in perl. The regex needs to be stored in a variable.

From this question I got

to match regex in a variable.

$regex = "\\$[0-9] (\\+|\\*) [0-9]";
$str = "$2 * 2";

if ($str =~ /\Q$regex/) { # regex is: \$[0-9] (\+|\*) [0-9]
print "Expression found :)\n";
} else {
print "Expression not found :(\n";

This matches fine in regexpal. It also works fine when I use the regex immediately without first putting it in
(i.e. without the
). What is the
doing to mess up my regex?


The \Q and \E pair can be used to escape all non-word characters within a double-quoted string context. For instance

perl -E 'say "abc[\Q[..]\E]def"'



I wonder why you think you need it, as it prevents all regex metacharacters from having their special effect. For instance \Q[0-9] will match exactly [0-9] instead of any single decimal digit

I would write your code like this. Note that I have changed double quotes to qr// when defining the pattern to create a compiled regex, and to single quotes when defining the target string to avoid Perl trying to interpolate built-in variable $2 into the string. You must always use strict and use warnings 'all' at the top of every Perl program you write

use strict;
use warnings 'all';

my $regex = qr/\$[0-9] [+*] [0-9]/;
my $str   = '$2 * 2';

if ( $str =~ $regex ) {
    print "Expression found :)\n";
else {
    print "Expression not found :(\n";


Expression found :)