in reply to Split a large array into 10 smaller arrays

I came across this looking for a better way than the one I spun. I prefer working with references on this sort of thing, so here is my spin on the AofA approach. This can work with an arbitrary number of arrays thanks to autovivification:

#!/usr/bin/env perl use strict; use warnings; use Data::Printer; my @original = (1,2,3,4,5,6,7,8,9); my $numberofarrays = 2; my @arrayrefs; while (@original) { foreach (0..$numberofarrays-1){ if (@original) { push @{$arrayrefs[$_]}, shift @original; } } } p @arrayrefs;

To get at the one you want, simply dereference it:

print "@{$arrayrefs[0]}\n";

Replies are listed 'Best First'.
Re^2: Split a large array into 10 smaller arrays
by Anonymous Monk on Apr 05, 2016 at 17:48 UTC

    I just checked list utils, and searched cpan for a package for this sort of thing. I found Array::Split which does exactly what I did - only without chewing through the original with pop. Using this package:

    #!/usr/bin/env perl use strict; use warnings; use Data::Printer; use Array::Split qw( split_into ); my @original = (1,2,3,4,5,6,7,8,9); my $numberofarrays = 2; my @arrayrefs = split_into($numberofarrays,@original);