Perl的1到9美元的范围是多少?

Nat*_*man 5 regex perl scope

Perl中的$1穿越范围是什么$9?例如,在此代码中:

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";
Run Code Online (Sandbox Code Playgroud)

$1是什么?这将是第一个\w*$x或第一\d*与第二\w*$x

Cha*_*ens 17

perldoc perlre

编号的匹配变量($ 1,$ 2,$ 3等)和相关的标点符号集($ +,$&,$`,$'和$ ^ N)都是动态范围的,直到封闭块的末尾或者直到下一场成功的比赛,以先到者为准.(参见perlsyn中的"复合陈述")

这意味着第一次在作用域中运行正则表达式或替换时,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";
Run Code Online (Sandbox Code Playgroud)

其中,$first$second有更好的名字来描述它们的内容.