How to create dynamic arrays in perl

I have a situation where the input is in a form $n

followed by lines n

containing elements of n

different arrays.
as

2  
1 2 3   
1 6   

      

means I have 2 arrays with elements like 1,2,3

and 1,6

.

Now I really don't know how big N can be. How to create dynamic arrays and store their value. Arrays can be named array1, array2, or any other method to distinguish between different arrays.

$n = <STDIN>;
for ($i = 0; $i < $n; $i++) {
    $l   = <STDIN>;
    @arr = split(" ", $l);
}

      

Please improve this code.

+3


source to share


1 answer


You can use an array of arrays:

use strict;    
my @array;
while(<STDIN>) {
    my @line = split(" ", $_);
    push @array, \@line;
}

# Just to display what inside your array:
use Data::Dumper;     
print Dumper(\@array);    

      



Or even shorter:

use strict;
my @array;
push @array, [split ' ', $_] while(<STDIN>);

      

+3


source







All Articles