Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Here is a Perl 6 solution in a single statement. It's probably not the best solution, but it does work today in rakudo:
my @l = <a bb c d e f g h>; sub chunky(@l, $len) { (0, $len ...^ *>=@l).map({@l[$_ .. ($_ + $len - 1 min @l.end)] ~ " +\n" }).join } print chunky(@l, 3);

The 0, $len ...^ *>=@l creates a list in steps of $len, up to (but excluding) the number of elements in @l.

Inside the map there is an array slice. The min @l.end is only necessary because Rakudo doesn't clip array slices to the end of the list yet (which is a known and reported bug).

I'm still looking for a nicer solution, will update my post if I find one.

Update: Nicer solution:

my @l = <a bb c d e f g h>; sub chunky(@l, $len) { (@l Z (' ' xx $len - 1, "\n") xx *).join.substr(0, -1) ~ "\n"; } print chunky(@l, 3);

This creates an infinite list (' ', ' ', "\n", ' ', ' ', "\n", ...), and then zips the input list with it. (zip = takes one item from each list in turn). Zips stops when the shortest list is exhausted, so we don't have to worry about it looping forever.

The result is then joined together, and the last separator is unconditionally substituted for a newline.

Perl 6 - links to (nearly) everything that is Perl 6.

In reply to Re: Rosetta code: Split an array into chunks by moritz
in thread Rosetta code: Split an array into chunks by eyepopslikeamosquito

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



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (8)
As of 2024-04-19 12:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found