Why splice when you can regex ?
#!/usr/bin/perl
use strict; # https://perlmonks.org/?node_id=861938
use warnings;
sub chunk_array
{
my $n = shift() - 1;
"@_\n" =~ s/(?: \S*){$n}\K /\n/gr;
}
my $v1 = chunk_array(3, "a", "bb", "c", "d", "e", "f", "g", "h");
$v1 eq "a bb c\nd e f\ng h\n" or die "error: '$v1'\n";
print $v1;
print "------------------------------\n";
my $v2 = chunk_array(3, "a", "bb", "c", "d", "e", "f");
$v2 eq "a bb c\nd e f\n" or die "error: '$v2'\n";
print $v2;
Outputs:
a bb c
d e f
g h
------------------------------
a bb c
d e f
Another one of the \K/r idiom that makes perl so great!
-
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.