Here is small perl snippet:
my $n = 1;
my $re_str = '\d';
my $re_str_q = '\Q1\E';
printf "re_str match: %s\n", ($n =~ /$re_str/);
printf "re_str_q match: %s\n", ($n =~ /$re_str_q/);
printf "direct match: %s\n", ($n =~ /\Q1\E/);
When run produces following output:
re_str match: 1
re_str_q match:
direct match: 1
So, my question here is why the second printf doesn't match ?
If you change
my $re_str_q = '\Q1\E'; #from
my $re_str_q = qr/\Q1\E/; #to
which would be the correct way to pass a dynamically generated regex, then it would give the following result
re_str match: 1
re_str_q match: 1
direct match: 1
Also if you had used
use strict;
use warnings;
you would get a warning
Unrecognized escape \Q passed through in regex; marked by <-- HERE in m/\Q <-- HERE 1\E/ at so.pl line 9.
Unrecognized escape \E passed through in regex; marked by <-- HERE in m/\Q1\E <-- HERE / at so.pl line 9.
Which would have given you some indication as to what was going wrong.
UPDATE
To understand this in further detail, you can read from here
The take away from the referenced document
The following escape sequences are available in constructs that interpolate, but not in transliterations.
\l lowercase next character only
\u titlecase (not uppercase!) next character only
\L lowercase all characters till \E or end of string
\U uppercase all characters till \E or end of string
\F foldcase all characters till \E or end of string
\Q quote (disable) pattern metacharacters till \E or
end of string
\E end either case modification or quoted section
(whichever was last seen)
See quotemeta for the exact definition of characters that are quoted by \Q .
\L , \U , \F , and \Q can stack, in which case you need one \E for each. For example:
say"This \Qquoting \ubusiness \Uhere isn't quite\E done yet,\E is it?";
This quoting\ Business\ HERE\ ISN\'T\ QUITE\ done\ yet\, is it?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With