2015-03-02 109 views
0
use strict; 

my $type = "build"; 
if ($type =~ (/build|test/)) 
{ 
    print "type=$1"; 
} 

我期望它打印“type = build”,但是$ 1没有得到任何东西,它打印出“type =”,我做错了什么?用Perl模式打印匹配的字符串匹配

+1

我认为这篇文章可以帮助你得到一个答案:http://stackoverflow.com/ question/24936145/perl-empty-1-regex-value-when-matching – Birei 2015-03-02 22:50:03

+4

提示:'使用警告' – TLP 2015-03-02 22:57:47

回答

2

它看起来像你没有捕捉您的括号什么,

perl -MO=Deparse -e' 
    use strict; 

    my $type = "build"; 
    if ($type =~ (/build|test/)) 
    { 
    print "type=$1"; 
    } 
    ' 

输出

use strict; 
my $type = 'build'; 
if ($type =~ /build|test/) { 
    print "type=$1"; 
} 

/(build|test)/应该完全是另一回事。

+0

我不明白你在这里说什么。你是否只是表明括号没有区别?这似乎不是解决问题的办法。 – Borodin 2015-03-03 06:49:26

+0

是的,解决方案是在答案的最后提出的。 – 2015-03-03 07:07:31

+0

好的。但*“'/(build | test)/'应该完全是另一回事了”*看起来不像是一个建议的解决方案,甚至是一个推荐! – Borodin 2015-03-03 07:09:30

1

你没有捕获你的正则表达式中的任何东西。你的括号必须的模式,这样

if ($type =~ /(build|test)/) { 
    print "type=$1"; 
} 
+0

是的,它的工作原理,谢谢。 – rodee 2015-03-02 22:54:56

+0

@Krish:如果这解决了你的问题,接受这个答案并关闭它。 – serenesat 2015-03-03 06:19:48

1

这就是人们在这里建议使用use warningsuse strict的原因。 如果你在你的代码添加use warnings,你会得到一个警告:

Use of uninitialized value $1 in concatenation (.) or string at type.pl line 7 

代码:

use warnings; 
use strict; 

my $type = "build"; 
if ($type =~ /(build|test)/) 
{ 
    print "type=$1"; 
}