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.

In reply to How to return a list using recursion? by dr.jekyllandme

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.