perl特殊变量$ - [0]和$ + [0]的含义是什么

Ano*_*eek 9 perl predefined-variables special-variables

我想知道perl的特殊变量的含义$-[0]$+[0]

我用google搜索,发现它$-代表页面上剩下的行数,$+代表最后一个搜索模式匹配的括号.

但我的问题是正则表达式的背景是什么$-[0]$+[0]意味着什么.

如果需要代码示例,请告诉我.

Den*_*aev 14

perldoc perlvar@+@-.

$+[0] 是整个匹配结束的字符串的偏移量.

$-[0] 是上次成功比赛开始的偏移量.


mat*_*ake 8

这些都是数组中的元素(由方括号和数字表示),因此您要搜索@ - (数组)而不是$ - (不相关的标量变量).

表扬

perldoc perlvar 
Run Code Online (Sandbox Code Playgroud)

解释了Perl的特殊变量.如果你在那里搜索@ - 你会发现.

$-[0] is the offset of the start of the last successful match. $-[n] is the offset of the start of the substring matched by n-th subpattern, or undef if the subpattern did not match.


小智 5

添加示例以更好地理解$-[0]$+[0]

还添加有关变量的信息 $+

use strict;
use warnings;

my $str="This is a Hello World program";
$str=~/Hello/;

local $\="\n"; # Used to separate output 

print $-[0]; # $-[0] is the offset of the start of the last successful match. 

print $+[0]; # $+[0] is the offset into the string of the end of the entire match. 

$str=~/(This)(.*?)Hello(.*?)program/;

print $str;

print $+;                    # This returns the last bracket result match 
Run Code Online (Sandbox Code Playgroud)

输出:

D:\perlex>perl perlvar.pl
10                           # position of 'H' in str
15                           # position where match ends in str
This is a Hello World program
 World
Run Code Online (Sandbox Code Playgroud)