[Solved] Perl: Separate array value by certain variable string


Iterate over the elements, store them into an array of arrays, resetting the index of the outer array on each Exit:

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my @arr = qw(John Eva Felix Exit a b c Exit 1 2 3);

my @out;
my $index = 0;

for (@arr) {
    if ('Exit' eq $_) {
        $index = 0;

    } else {
        push @{ $out[$index++] }, $_;
    }
}

say join ' ', @$_ for @out;

If the input lines aren’t of the same length, you can assign to the particular element in the array:

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

my @arr = qw(John Eva Felix Exit a b c d e f Exit 1 2 3 4);

my @out;
my $outer = 0;
my $inner = 0;

for (@arr) {
    if ('Exit' eq $_) {
        $outer = 0;
        ++$inner;

    } else {
        $out[$outer++][$inner] = $_;
    }
}

say join "\t", map $_ // q(), @$_ for @out;

7

solved Perl: Separate array value by certain variable string