Perl:里面有变量的正则表达式?

Perl: Regex with Variables inside?

有没有比这更优雅的方式将变量引入模式(之前将模式放在字符串中而不是直接在 // 中使用它)??

my $z = "1";  # variable
my $x = "foo1bar";

my $pat = "^foo".$z."bar$";   
if ($x =~ /$pat/)
{
  print "\nok\n";
}

qr operator做到了

my $pat = qr/^foo${z}bar$/;

除非分隔符是 ',在这种情况下它不会插入变量。

此运算符是提前构建模式的最佳方式,因为它构建了适当的正则表达式模式,接受可以在正则表达式中的模式中使用的所有内容。它还带有修饰符,因此上面的一个可以写成

my $pat = qr/^foo $z bar$/x;

为了更清楚一点(但要小心省略那些 {})。

上面perlop link的初步描述(示例和讨论如下):

qr/STRING/msixpodualn

This operator quotes (and possibly compiles) its STRING as a regular expression. STRING is interpolated the same way as PATTERN in m/PATTERN/. If "'" is used as the delimiter, no variable interpolation is done. Returns a Perl value which may be used instead of the corresponding /STRING/msixpodualn expression. The returned value is a normalized version of the original pattern. It magically differs from a string containing the same characters: ref(qr/x/) returns "Regexp"; however, dereferencing it is not well defined (you currently get the normalized version of the original pattern, but this may change).


一旦变量被插值,转义可能隐藏在其中的特殊字符可能是个好主意,这可能会抛出正则表达式,使用 quotemeta 基于 \Q ... \E

my $pat = qr/^foo \Q$z\E bar$/x;

如果使用这个变量名也不需要定界

my $pat = qr/^foo\Q$z\Ebar$/;

感谢 Håkon Hægland 提出这个问题。