Regexp在Perl中搜索和替换为变量

Chr*_*s R 2 regex perl

我无法找到解决方案,它让我疯狂!

my $foo = qr/(\S+) (\X+)/;
my $bar = qr/$2/;

line =~ s/$foo/$bar/g 
Run Code Online (Sandbox Code Playgroud)

我的问题是$bar使用先前定义的值$2而不是(\X+).

bvr*_*bvr 5

请注意,第二部分s不是正则表达式,而是字符串来替换发现的正则表达式.你可以用这个来实现你想要的东西(注意最后的ee双重评估选项):

my $foo = qr/(\S+) (\X+)/;
my $bar = '$2';             # no interpolation

$line =~ s/$foo/$bar/gee;   # first eval make $bar -> '$2', second replaces it 
Run Code Online (Sandbox Code Playgroud)