简体   繁体   English

Perl在数组文件中的特定行之间存储数据

[英]Perl store data in between particular lines from a file in an array

Say, I have this data in a file: 说,我在文件中有此数据:

start
1
5
6
start
4
5
start
6
end

I want this data to be stored in array of arrays like 我希望这些数据存储在像这样的数组数组中

([1,5,6],[4,5],[6])

I tried it with flip flop operator: 我用触发器运算符尝试过:

if(/start/../start/){
                my $line=<DATA>;
                print "$line \n";
                push(@data,$line) if($line=~/start/);
        }
}

It didn't worked for me. 它对我没有用。 Any suggestions and help is greatly appreciated. 任何建议和帮助,我们将不胜感激。

I suggest you use the algorithm encoded below 我建议您使用下面编码的算法

It reads the file line by line, accumulating each value into array @item . 它逐行读取文件,将每个值累加到数组@item If a line contains start or end then it is considered to be a boundary, and instead of adding to @item , its contents are copied as a block into @data ; 如果一行包含startend则将其视为边界,而不是将其添加到@item ,而是将其内容作为块复制到@data then @item is emptied 然后@item被清空

use strict;
use warnings;

my (@data, @item);

while ( <DATA> ) {

    chomp;

    if ( /start|end/ ) {
        if ( @item ) {
            push @data, [ @item ];
            @item = ();
        }
    }
    else {
        push @item, $_;
    }
}

use Data::Dump;
dd \@data;

__DATA__
start
1
5
6
start
4
5
start
6
end

output 产量

[[1, 5, 6], [4, 5], [6]]

I probably wouldn't use a range operator, and instead set $/ to start\\n . 我可能不会使用范围运算符,而是将$/设置为start\\n

EG 例如

local $/ = "start\n";
my @stuff;
while ( <DATA>) {
     my @chunk = m/(\d+)/gm;
     push ( @stuff, \@chunk) if @chunk;
}
print Dumper \@stuff ;

Something like that anyway. 反正就是这样。

output 产量

$VAR1 = [
          [
            '1',
            '5',
            '6'
          ],
          [
            '4',
            '5'
          ],
          [
            '6'
          ]
        ];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM