Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: How to return a list using recursion?

by tobyink (Canon)
on Aug 07, 2012 at 05:45 UTC ( [id://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'

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (2)
As of 2024-04-26 04:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found