2012-06-25 24 views
10

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

我用Google搜索,发现$-代表留下的行数该页面和$+代表最后一个搜索模式匹配的最后一个括号。

但我的问题是什么$-[0]$+[0]意味着正则表达式的上下文。

让我知道是否需要代码示例。

+1

你看了perlvar的perldoc? http://perldoc.perl.org/perlvar.html'$ + [0]'上的例子非常清晰。 –

+0

你应该更熟悉[手册] [1]。 –

+5

你正在寻找的变量是'@ -'和'@ +'。 – flesk

回答

13

请参阅perldoc perlvar@+@-

$+[0]是整个比赛结束字符串的偏移量。

$-[0]是上次成功匹配开始时的偏移量。

8

这些都是数组中的元素(用方括号和数字表示),所以您要搜索@ - (数组)而不是$ - (一个不相关的标量变量)。

的表彰

perldoc perlvar 

解释了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

4

添加例如更好地理解$-[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 

输出也增加了信息:

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 
+1

感谢您的好例子。 @ + @ - $ - $ +的概念现在对我来说已经完全清楚了......但这对于未来的游客肯定会有所帮助+1 – AnonGeek

相关问题