Perl,动态生成的regexp字符串,带有反斜杠的元字符奇怪的行为

Dfr*_*Dfr 2 regex perl

这是一个小的perl片段:

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/);
Run Code Online (Sandbox Code Playgroud)

运行时产生以下输出:

re_str   match: 1
re_str_q match: 
direct match: 1
Run Code Online (Sandbox Code Playgroud)

所以,我的问题是为什么第二个printf不匹配?

Ame*_*mey 9

如果你改变了

my $re_str_q = '\Q1\E'; #from 
my $re_str_q = qr/\Q1\E/; #to
Run Code Online (Sandbox Code Playgroud)

这将是传递动态生成的正则表达式的正确方法,然后它将给出以下结果

re_str   match: 1
re_str_q match: 1
direct match: 1
Run Code Online (Sandbox Code Playgroud)

如果你曾经使用过

use strict;
use warnings;
Run Code Online (Sandbox Code Playgroud)

你会收到警告

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.
Run Code Online (Sandbox Code Playgroud)

哪个会给你一些关于出错的迹象.

UPDATE

要进一步了解这一点,您可以从这里阅读

摘录参考文件

以下转义序列在构造中可用interpolate,但不在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)
Run Code Online (Sandbox Code Playgroud)

有关\ Q引用的字符的确切定义,请参阅quotemeta.

\ L,\ U,\ F和\ Q可以叠加,在这种情况下,每个都需要一个\ E. 例如:

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?
Run Code Online (Sandbox Code Playgroud)