Hello,
I need help writing a recursive subroutine that will return an array. I would like to do something similar to PHP's array_chunk. Let's say I have a list of elements:
@list = ( 'a' .. 'z' );
I want to set a limit of 5 characters for each array element separated by spaces and ending in a comma if the array will have more elements following it. The expected output:
a b c d e, # arr[0]
f g h i j, # arr[1]
k l m n o, # arr[2]
p q r s t, # arr[3]
u v w x y, # arr[4]
z # arr[5]
So far, I have achieved this output by returning a string separated by newlines. I could get a list at this point by splitting on newline, but I would like to get a list instead. The only problem is that I am not sure how to return a list using recursion. My code so far:
#!usr/bin/perl
use strict;
use warnings;
my @list = ( 'a' .. 'z' );
my $string_chunk5 = _string_chunk5( @list );
my @array_chunk5 = _array_chunk5( @list );
print "String chunk of 5 =\n$string_chunk5\n";
print "Array chunk of 5 =\n@array_chunk5\n";
sub _string_chunk5 {
my @arr = @_;
return join( " ", @arr ) unless @arr > 5;
return join( " ", splice( @arr, 0, 5 ) ). ",\n" . _string_chunk5(
+@arr );
}
sub _array_chunk5 {
my @arr = @_;
# Base case == when @arr is <= 5
return ( join( " ", @arr ) ) unless @arr > 5;
# what goes here ?
}
Any pointers would be a great help. Thank you for your time.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.