简体   繁体   中英

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 . 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 ; then @item is emptied

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 .

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'
          ]
        ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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