2015-05-20 37 views
0

我正在開發一個Perl腳本,其中一個腳本函數是檢測兩個終端之間的多行數據並將它們存儲在數組中。我需要將所有行存儲在一個數組中,但要分別編號爲$1中的第1行和$2中的第2行等。這裏的問題是這些行的數量是可變的,並且隨着每次新的運行而改變。Perl:正則表達式:在數組中存儲可變行

my @statistics_of_layers_var; 
for(<ALL_FILE>) { 
    @statistics_of_layers_var = ($all_file =~ /(Statistics\s+Of\s+Layers) 
    (?:(\n|.)*)(Summary)/gm); 
    print @statistics_of_layers_var; 

給出的數據應該是

Statistics Of Layers 
Line#1 
Line#2 
Line#3 
... 
Summary 

我怎麼能實現呢?

回答

0

也許你可以試試這個:

push @statistics_of_layers_var ,[$a] = ($slurp =~ /(Statistics\s+Of\s+Layers) 
(?:(\n|.)*)(Summary)/gm); 
+0

它給了我編譯它時不能修改標量賦值錯誤的匿名列表([]),任何想法爲什麼在你的答案中這個新的編輯會導致這個錯誤? –

2

你可以做到這一點而無需複雜的正則表達式。只需使用range operator(也稱爲觸發器操作符)來查找所需的行。

use strict; 
use warnings; 
use Data::Printer; 

my @statistics_of_layers_var; 
while (<DATA>) { 
    # use the range-operator to find lines with start and end flag 
    if (/^Statistics Of Layers/ .. /^Summary/) { 
     # but do not keep the start and the end 
     next if m/^Statistics Of Layers/ || m/^Summary/; 
     # add the line to the collection 
     push @statistics_of_layers_var, $_ ; 
    } 
} 

p @statistics_of_layers_var; 

__DATA__ 
Some Data 
Statistics Of Layers 
Line#1 
Line#2 
Line#3 
... 
Summary 
Some more data 

它通過查看當前行並打開和關閉塊來工作。如果/^Statistics of Layers/與該行匹配,它將爲每個後續行運行該塊,直到`/^Summary /匹配一行。由於包含這些開始和結束行,我們需要在將數據行添加到數組時跳過它們。

這也適用於如果您的文件包含此模式的多個實例。然後你會得到數組中的所有行。