如何在替换的正则表达式部分将变量插入正则表达式模式?

How to interpolate a variable into a regex-pattern in the regex part of a substitution?

我必须在此处更改什么才能使其正常工作?

my $str = "start middle end";
my $regex = / start ( .+ ) end /;
$str.=subst( / <$regex> /, { [=10=] } ); # dies: Use of Nil in string context
say "[$str]";

问题是通过 <$regex> 语法将一个正则表达式插入另一个正则表达式不会将结果安装到匹配变量中。有两种方法可以解决这个问题:

  • 最简单的方法是直接在 subst 中使用正则表达式,即 $str .= subst($regex, { [=11=] });
  • 为内插正则表达式指定一个显式名称并通过该名称访问结果,即 $str .= subst( / <foo=$regex> /, { $<foo>[0] });

这两个应该都能正常工作。