http://www.perlmonks.org?node_id=985886


in reply to How to return a list using recursion?

I agree that this isn't necessarily the best task to use recursion for, but here's one possibility:

use Data::Dumper; sub mk_chunker { my $n = shift; die unless $n > 0; my $sub; return $sub = sub { return \@_ if @_ < $n; return ( [ @_[0..$n-1] ], $sub->(@_[$n..$#_]), # recursion ); }; } *chunk_5 = mk_chunker(5); print Dumper chunk_5('a' .. 'z');

The closure in mk_chunker is a good candidate for Perl 5.16's new __SUB__ feature...

use 5.016; sub mk_chunker { my $n = shift; die unless $n > 0; return sub { return \@_ if @_ < $n; return ( [ @_[0..$n-1] ], __SUB__->(@_[$n..$#_]), # recursion ); }; }
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'