Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re^3: How to return a list using recursion?

by Anonymous Monk
on Aug 07, 2012 at 15:04 UTC ( #986016=note: print w/ replies, xml ) Need Help??


in reply to Re^2: How to return a list using recursion?
in thread How to return a list using recursion?

With older versions of Perl, it can be rewritten as a proper iterator :-)

use strict; use warnings; my @list = ('a' .. 'z'); my $size = 5; my $chunker = _array_chunk_it($size, @list); while (my @chunk = $chunker->()) { print "Array chunk of $size =\n", join("\n", @chunk), "\n\n"; } sub _array_chunk_it { my ($count, @array) = @_; return sub { my @chunk; for (1 .. $count) { push(@chunk, shift @array) if @array; } return @chunk; } }

(Using a closure we can actually call _array_chunk_it multiple times, in an overlapping manner. Have multiple iterators running simultaneously. Plus it looks quite a bit nicer.)


Comment on Re^3: 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://986016]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (8)
As of 2015-07-06 22:42 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 (84 votes), past polls