0

我有一个包含以下内容的输出文件。我想根据“模式”将它分成块并存储在一个数组中。

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

第n和第 ( n +1)“模式”出现之间的内容是一个块:

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 中实现

4

2 回答 2

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
于 2012-05-17T11:00:02.547 回答
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
于 2012-05-17T13:40:36.450 回答