regex - Perl 中 $1 到 $9 的范围是什么?

标签 regex perl scope

$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 ?

最佳答案

来自 perldoc perlre

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/

相关文章:

javascript - 确定 JavaScript 闭包中可访问的变量集

javascript - 正则表达式用于字母数字字符,而不仅仅是数字

java - 按字符数字拆分字符串

python - 计算原子坐标之间的距离

perl - 如何让 Perl 在读取用户输入时识别 Shift-Tab

python - 模块对象访问 Jupyter 笔记本单元中的 "global"值

scope - Kotlin - 限制扩展方法范围

php - 将数学表达式拆分为数组而不拆分括号和单引号之间的子表达式

regex - 使用正则表达式在 MongoDB 的物化路径中获取直接后代

arrays - 查找与第二个数组的元素匹配的数组元素