in reply to Dividing an array into multiple parts

Like this?
use warnings; use strict; use Data::Dumper; my @a; my @b; @a = (1..100); @b = (1..8); print Dumper ( divarray(\@a, \@b) ); @a = (1..5); @b = (1..8); print Dumper ( divarray(\@a, \@b) ); sub divarray { my @a = @{shift @_}; my @b = @{shift @_}; my @c; my $i = 0; my $b = int(@a/@b)+1; for ( @a ) { push @c, [] if $i == 0 or $i % $b == 0; push @{$c[-1]}, $_; $i++; } return \@c; }
Thinking about it for a minute, this is an improved version of the function:
sub divarray { my @a = @{shift @_}; my @b = @{shift @_}; my @c; my $b = int(@a/@b)+1; while ( @a ) { push @c, [splice (@a, 0, $b)]; } return \@c; }


holli, /regexed monk/

Replies are listed 'Best First'.
Re^2: Dividing an array into multiple parts
by tsk1979 (Scribe) on Mar 16, 2006 at 11:58 UTC
    Thanks! I guess this creates a third array c in which each element is an array composed of the elements of a