Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks, I have a newbie question:

I have an array of info (size will vary but always multiple of 30) that I want to divide into new arrays each containing 30 elements.

How can I do this when the size will vary?

Thanks!

Replies are listed 'Best First'.
Re: dividing up arrays
by friedo (Prior) on Jan 10, 2005 at 11:38 UTC
    How about something like:

    my @data = get_big_array; my @new; my $i; for( $i = 0; $i < $#data; $i+=30 ) { push @new, [ @data[$i..($i+29)] ]; }
Re: dividing up arrays
by gellyfish (Monsignor) on Jan 10, 2005 at 11:48 UTC

    If you don't mind destroying your array or can make a copy of it then you could use splice:

    my @foo = (1 .. 154); + my @bar; + while ( my @sp = splice @foo, 0, 30 ) { push @bar, \@sp; } + foreach my $zub (@bar) { print "@{$zub}\n"; }

    /J\

Re: dividing up arrays
by macPerl (Beadle) on Jan 10, 2005 at 14:15 UTC
    Do you ever need the data as one big array ? Maybe you should consider setting up an array of that holds references to sub-arrays each of which has 30 elements.

    If (like me :-]) you are a Perl novice there is a great explanation of using references in your perl documentation: look for perlreftut.html.
Re: dividing up arrays
by Anonymous Monk on Jan 10, 2005 at 15:18 UTC
    Untested:
    my @newarrays; my @bigoldarray; push @newarrays, [splice @bigoldarray, 0, 30] while @bigoldarray;