2013-08-12 26 views
1

我試圖尋找在這樣的多行輸入串中的某個關鍵字,處理多行輸入 - 環路VS正則表達式

this is input line 1 
this is the keyword line 
this is another input line 
this is the last input line 

多行輸入存儲在一個變量,名爲「$輸入數據」。現在,我心裏有2種方式來尋找「關鍵字」這個詞,

方法1:
採用分體式放線到一個數組中使用「\ n」分隔符,並使用迭代和過程中的每個線foreach循環,這樣,

my @opLines = split("\n", $inputData); 

# process each line individually 
foreach my $opLine (@opLines) 
{ 
    # look for presence of "keyword" in the line 
    if(index($opLine, "keyword") > -1) 
    { 
     # further processing 
    } 
} 


方法2:
使用正則表達式,如下面,

if($inputData =~ /keyword/m) 
{ 
    # further processing 
} 


我想知道這兩種方法是如何相互比較的,以及關於實際代碼性能和執行時間的更好方法是什麼。另外,是否有更好,更有效的方法來完成這項任務?

回答

2
my @opLines = split("\n", $inputData); 

將創建變量@opLines,分配內存,並搜索"\n"槽全$inputData和寫入發現行了進去。

# process each line individually 
foreach my $opLine (@opLines) 
{ 

將處理爲每個值的一大堆代碼在陣列@opLines

# look for presence of "keyword" in the line 
    if(index($opLine, "keyword") > -1) 

將搜索在每行的"keyword"

{ 
     # further processing 
    } 
} 

而且comapare

if($inputData =~ /keyword/m) 

將搜索"keyword"和停止時找到第一次出現。

{ 
    # further processing 
} 

現在猜測,什麼會更快,消耗更少的內存(這也會影響速度)。如果你猜測使用Benchmark模塊不好。

根據documentationm正則表達式改性劑:款待字符串作爲多行。也就是說,將「^」和「$」從僅匹配字符串左端和右端的行的開頭或結尾更改爲匹配字符串中的任何位置。我在你的正則表達式中既沒有看到^也沒有看到$,所以它在那裏沒用。

+0

感謝您的好評!沒有真正用^和$來得到最後一部分,你能澄清嗎?對不起,對於正則表達式有點新... –

+0

除非在正則表達式中使用'^'或'$',否則您不必在regexp之後使用'm'修飾符。它會起作用。 –