2012-05-17 30 views
0

我有一個包含以下內容的輸出文件。我想根據「模式」將它分成塊並存儲在一個數組中。如何根據模式將輸出文件分割爲多個塊

Sample output: 
100 pattern 
line 1 
line 2 
line 3 
101 pattern 
line 4 
102 pattern 
line 5 
line 6 
... 

內容第和(Ñ 1)個 「模式」 的發生之間的N個是嵌段:

Block 1: 
100 pattern 
line 1 
line 2 
line 3 

Block 2: 
101 pattern 
line 4 


Block 3: 
102 pattern 
line 5 
line 6 

基本上我跨越搜索的圖案並將其中的內容存儲到數組中。

請讓我知道我怎麼在Perl

+0

將文件讀入數組中。將數組內容加入單個字符串中,然後在模式中分割。 – Unos

+0

保證模式是基於單線的?你想要一個塊是數組的元素還是元素應該是行?你的模式的性質是什麼? – ArtM

+3

到目前爲止你做了什麼?困難究竟是什麼? –

回答

3

實現假設你模式是全行方含字pattern(和正常行不),你想數組元素是整個塊:

my @array; 
my $i = 0; 

for my $line (<DATA>) { 
    $i++ if ($line =~ /pattern/); 
    $array[$i] .= $line; 
} 

shift @array unless defined $array[0]; # if the first line matched the pattern 
1

我知道你已經接受了答案,但我想告訴你如何通過讀取數據並使用正則表達式來分解它。

#!/usr/bin/perl 

use strict; 
use warnings; 

use 5.010; 

my $input = do { local $/; <DATA> }; 

my @input = split /(?=\d+ pattern)/, $input; 

foreach (0 .. $#input) { 
    say "Record $_ is: $input[$_]"; 
} 

__DATA__ 
100 pattern 
line 1 
line 2 
line 3 
101 pattern 
line 4 
102 pattern 
line 5 
line 6 
相關問題