$1
的范围是什么?通过 $9
在 Perl 中?例如,在这段代码中:
sub bla {
my $x = shift;
$x =~ s/(\d*)/$1 $1/;
return $x;
}
my $y;
# some code that manipulates $y
$y =~ /(\w*)\s+(\w*)/;
my $z = &bla($2);
my $w = $1;
print "$1 $2\n";
什么会
$1
是?会不会是第一个\w*
来自 $x
还是第一个\d*
来自第二个 \w*
在 $x
?
最佳答案
The numbered match variables ($1, $2, $3, etc.) and the related punctuation set ($+ , $& , $` , $' , and $^N ) are all dynamically scoped until the end of the enclosing block or until the next successful match, whichever comes first. (See ""Compound Statements"" in perlsyn.)
这意味着您第一次在范围内运行正则表达式或替换时会出现一个新的
local
已创建化副本。当范围结束时恢复原始值(à la local)。所以,$1
在正则表达式运行之前将是 10,在正则表达式之后是 20,在子例程完成时又是 10。但我不在替换之外使用正则表达式变量。我发现说这样的话要清楚得多
#!/usr/bin/perl
use strict;
use warnings;
sub bla {
my $x = shift;
$x =~ s/(\d*)/$1 $1/;
return $x;
}
my $y = "10 20";
my ($first, $second) = $y =~ /(\w*)\s+(\w*)/;
my $z = &bla($second);
my $w = $first;
print "$first $second\n";
哪里
$first
和 $second
有更好的名称来描述它们的内容。
关于regex - Perl 中 $1 到 $9 的范围是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1052976/