Create an array of arrays from a list in Perl -


i want create array of arrays list of objects. how reset array variable (@row , reuse hold items in next sections)? know @row declared once, when pushed array, emptying empty @arrays too. how can reset @row while not empty @arrays?

 use data::dumper;      # sample data, long list complex data types     @list = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);      @arrays;     @row;     $numsub = 10;      foreach $itm (@$list)  {        if (scalar(@row) == $numsub)         {              push @arrays, \@row;           @row = (); # clear array, cleared array of arrays           push @row, $itm;         }         else {           push @row, $itm;        }    }    # push last reminder     push @arrays, \@row;     dumper @arrays; # nothing  

put my @row inside of foreach loop instead of outside. distinct variable every time through loop.

incidentally, there nicer ways write this, example:

my @copy = @list; while (@copy) {   push @arrays, [ splice @copy, 0, $numsub ]; } 

or

use list::util 'max'; (my $i = 0 ; $i < @list ; $i += $numsub) {   push @arrays, [ @list[ $i .. max($i + $numsub, $#list) ] ]; } 

or

use list::moreutils 'natatime'; $iter = natatime $numsub, @list; while (my @vals = $iter->()) {   push @arrays, \@vals; } 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -