2015-03-02 112 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"; 
}