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

Exactly, my first thought was also splice

my take on it

use strict; use warnings; use Test::More; sub chunks { my ( @list ) = @_ ; my $count = 3; my $str = ""; while (my @cols = splice @list, 0, $count ) { $str .= "@cols\n"; } return $str; } # ========= Tests is( chunks("a", "bb", "c", "d", "e", "f", "g", "h") => <<'__CHUNK__', "Rosetta's Example" ); a bb c d e f g h __CHUNK__ is( chunks() => "", "Empty" ); done_testing;

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

Replies are listed 'Best First'.
Re^3: Rosetta code: Split an array into chunks
by LanX (Saint) on Oct 22, 2021 at 17:45 UTC
    Even shorter and faster (and most probably also memory efficient)

    use strict; use warnings; use Test::More; sub chunks { my $str = ""; while (my @cols = splice @_, 0, 3) { $str .= "@cols\n"; } return $str; } # ========= Tests my @list = ("a", "bb", "c", "d", "e", "f", "g", "h"); my @old = @list; my $text = "a bb c\n" . "d e f\n" . "g h\n" ; is( chunks(@list) => $text, "Rosetta's Example"); is( chunks() => "", "Empty string" ); is( chunks("") => "\n", "Empty List" ); is_deeply( \@list, \@old, "Non destructive! yeah ... :)"); done_testing;

    NB: @_ is a array of aliases, not an alias itself. Destryoing it doesn't affect the argument given :)

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

Re^3: Rosetta code: Split an array into chunks
by tybalt89 (Monsignor) on Oct 22, 2021 at 17:57 UTC

    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!

      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