2013-06-30 138 views
3

我有以下腳本:GREP獲得包含特定字符串的所有字符串

use strict; 
use warnings; 

my @test = ("a", "b", "c", "a", "ca"); 
my @res = grep(m#a#, @test); 

print (join(", ", @res)."\n"); 

它應該僅返回包含a字符串。它完美的作品。

問題是我需要能夠動態地獲取這些字符串。 我試過如下:

use strict; 
use warnings; 

my $match = "a"; 
my @test = ("a", "b", "c", "a", "ca"); 
my @res = grep($match, @test); 

print (join(", ", @res)."\n"); 

結果是:

A,B,C,A,CA

我應該怎麼做才能夠grep的陣列一個動態變量?

回答

11

grep發生在您提供的第二個參數,檢查第一個參數是否是真還是假的列表中的每個元素。在你的情況下,$match將永遠是真實的,因爲它永遠是「a」。試試這個:

my @res = grep(m/$match/, @test); 

如果您的動態字符串可以包含的不僅僅是字母數字字符越多,你也應該引用它:

my @res = grep(m/\Q$match/, @test); 
4

我想你想:

my @res = grep { $_ =~ $match } @test; 
相關問題