splice
して push
する。破壊的なので注意。
use strict; use warnings; sub chunk { my $ary = shift @_; my $n = shift @_; my $result = []; while (@$ary) { my @s = splice(@$ary, 0, $n); push(@$result, \@s); } return $result; } my $array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; print("array:", @$array, "\n"); my $chunked = chunk($array, 3); foreach my $c (@$chunked) { print("chunk:", @$c); print("\n"); } print("array:", @$array, "\n");
^o^ > perl chunk.pl array:0123456789 chunk:012 chunk:345 chunk:678 chunk:9 array: