Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: How to return a list using recursion?

by tobyink (Abbot)
on Aug 07, 2012 at 05:45 UTC ( #985886=note: print w/ replies, xml ) Need Help??


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'


Comment on Re: How to return a list using recursion?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://985886]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (18)
As of 2015-07-06 20:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (83 votes), past polls