繁体   English   中英

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

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

说,我在文件中有此数据:

start
1
5
6
start
4
5
start
6
end

我希望这些数据存储在像这样的数组数组中

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

我用触发器运算符尝试过:

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

它对我没有用。 任何建议和帮助,我们将不胜感激。

我建议您使用下面编码的算法

它逐行读取文件,将每个值累加到数组@item 如果一行包含startend则将其视为边界,而不是将其添加到@item ,而是将其内容作为块复制到@data 然后@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

产量

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

我可能不会使用范围运算符,而是将$/设置为start\\n

例如

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

反正就是这样。

产量

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

暂无
暂无

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

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