1

我发现反向引用 ($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。预先感谢您的帮助。

4

2 回答 2

3

您没有捕获任何字符串:您的模式中没有括号。如果你做了:

my $pattern = "(silly)";

你会得到一些东西$1

如果您不知道,$1是第一个括号中捕获的文本,$2第二个括号,依此类推。

于 2013-06-09T22:07:29.143 回答
2

这是预期的行为!很明显,您的模式将匹配,因此执行相应的 -block 也就不足为奇了if

术语“反向引用”$1, $2, ...可能不太理想,我们称它们为“捕获组”。

在正则表达式中,您可以用括号括起来部分模式,以便以后记住:

/(silly)/

这种模式有一组。$1如果匹配,该组的内容将被存储。

模式中不存在或未填充的组的所有捕获组变量都设置为undef否则成功匹配,因此对于上述模式$2, $3, ...将全部为undef.

于 2013-06-09T22:11:15.733 回答