替换中的空白替换会将匹配的字符串更改为空
blank substitute inside a substitution changes matched string to empty
我正在尝试以下一段代码。根据我的理解,基本上这段代码不应该改变 $data 。我错过了什么吗?我正在使用 5.22.3(草莓 perl)。
use strict;
use warnings;
use 5.010;
my $data = 'we are here';
$data =~ s///g;
print "DATA1: $data\n";
$data =~ s{(we)}{
my $x1 = ;
$x1 =~ s///g;
print "x1: ^^$x1^^\n";
"$x1"
}e;
print "DATA2: $data\n";
O/P-
DATA1: we are here
x1: ^^^^
DATA2: are here
除非被 split
使用,否则空模式告诉 match/substitute 运算符使用最后一个模式来成功匹配。
例如,
$ perl -e'$_ = "abba"; s//c/g if /a/ || /b/; CORE::say;'
cbbc
这意味着
$x1 =~ s///g;
等同于
$x1 =~ s/(we)//g;
要绕过该异常,您可以使用
$x1 =~ s/(?:)//g;
说你的真实情况使用
$re = ...;
s/$re//g;
你可以使用
$re = ...;
s/(?:$re)//g;
或
$re = ...;
$re = qr/$re/;
s/$re//g;
引用 perlop,
The empty pattern //
If the PATTERN evaluates to the empty string, the last successfully matched regular expression is used instead. In this case, only the g
and c
flags on the empty pattern are honored; the other flags are taken from the original pattern. If no match has previously succeeded, this will (silently) act instead as a genuine empty pattern (which will always match).
我正在尝试以下一段代码。根据我的理解,基本上这段代码不应该改变 $data 。我错过了什么吗?我正在使用 5.22.3(草莓 perl)。
use strict;
use warnings;
use 5.010;
my $data = 'we are here';
$data =~ s///g;
print "DATA1: $data\n";
$data =~ s{(we)}{
my $x1 = ;
$x1 =~ s///g;
print "x1: ^^$x1^^\n";
"$x1"
}e;
print "DATA2: $data\n";
O/P-
DATA1: we are here
x1: ^^^^
DATA2: are here
除非被 split
使用,否则空模式告诉 match/substitute 运算符使用最后一个模式来成功匹配。
例如,
$ perl -e'$_ = "abba"; s//c/g if /a/ || /b/; CORE::say;'
cbbc
这意味着
$x1 =~ s///g;
等同于
$x1 =~ s/(we)//g;
要绕过该异常,您可以使用
$x1 =~ s/(?:)//g;
说你的真实情况使用
$re = ...;
s/$re//g;
你可以使用
$re = ...;
s/(?:$re)//g;
或
$re = ...;
$re = qr/$re/;
s/$re//g;
引用 perlop,
The empty pattern //
If the PATTERN evaluates to the empty string, the last successfully matched regular expression is used instead. In this case, only the
g
andc
flags on the empty pattern are honored; the other flags are taken from the original pattern. If no match has previously succeeded, this will (silently) act instead as a genuine empty pattern (which will always match).