0

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.

2 Answers 2

3

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]]
Sign up to request clarification or add additional context in comments.

Comments

0

I probably wouldn't use a range operator, and instead set $/ to start\n.

E.G.

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

1 Comment

Almost! push @stuff, \@chunk if @chunk fixes it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.