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!
In reply to Re^3: Rosetta code: Split an array into chunks
by tybalt89
in thread Rosetta code: Split an array into chunks
by eyepopslikeamosquito
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |