我觉得奇怪的是,反向引用($ 1,$ 2,$ 3)在原始代码中不起作用,所以我从网上运行了这个例子:
#!/usr/bin/perl
# matchtest2.plx
use warnings;
use strict;
$_ = '1: A silly sentence (495,a) *BUT* one which will be useful. silly (3)';
my $pattern = "silly";
if (/$pattern/) {
print "The text matches the pattern '$pattern'.\n";
print "\$1 is '$1'\n" if defined $1;
print "\$2 is '$2'\n" if defined $2;
print "\$3 is '$3'\n" if defined $3;
print "\$4 is '$4'\n" if defined $4;
print "\$5 is '$5'\n" if defined $5;
}
else {
print "'$pattern' was not found.\n";
}
只给了我:
The text matches the pattern 'silly'.
为什么在发现模式后仍然未定义反向引用?我使用的是Wubi(Ubuntu 12.04 64位),我的perl版本是5.14.2。提前感谢您的帮助。
答案 0 :(得分:3)
您没有捕获任何字符串:您的模式中没有括号。如果你做了:
my $pattern = "(silly)";
你会在$1
获得一些东西。
如果您不知道,$1
是在第一个括号中捕获的文本,$2
是第二个括号,依此类推。
答案 1 :(得分:2)
这是预期的行为!很明显,你的模式会匹配,所以执行相应的if
- 块并不奇怪。
$1, $2, ...
的“反向引用”一词可能略微不理想,我们称之为“捕获组”。
在正则表达式中,您可以将模式的一部分用parens包围起来以便以后记住:
/(silly)/
此模式有一个组。如果匹配,该组的内容将存储在$1
中。
模式中不存在或未填充的组的所有捕获组变量在其他成功匹配时设置为undef
,因此对于上述模式$2, $3, ...
,所有变量都将{{1} }}