【问题标题】:Backreferences undefined after finding pattern in perl v5.14.2在 perl v5.14.2 中找到模式后未定义的反向引用
【发布时间】:2013-06-09 21:57:16
【问题描述】:

奇怪的是,反向引用 ($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。提前感谢您的帮助。

【问题讨论】:

  • 你期待什么输出?
  • 你没有捕捉到模式,傻瓜。
  • @doubleDown 反正这种模式很傻。
  • 大声笑,我 1 美元。谢谢

标签: perl undefined backreference


【解决方案1】:

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

my $pattern = "(silly)";

你会在$1得到一些东西。

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

【讨论】:

  • 非常感谢您的回答!
【解决方案2】:

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

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

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

/(silly)/

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

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

【讨论】:

  • 非常感谢您的回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
  • 1970-01-01
  • 2012-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多