2012-05-17 31 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 
相关问题