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:@list = ( 'a' .. 'z' );
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: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]
Any pointers would be a great help. Thank you for your time.#!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 ? }
In reply to How to return a list using recursion? by dr.jekyllandme
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |