in reply to Re^2: Rosetta code: Split an array into chunks
in thread Rosetta code: Split an array into chunks

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!

Replies are listed 'Best First'.
Re^4: Rosetta code: Split an array into chunks
by LanX (Saint) on Oct 22, 2021 at 18:01 UTC
    I'm surprised your username doesn't contain multiple / and 99

    The gods would certainly grant your wish to transform it into an unreadable regex ... ;-P

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery