Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re^3: Rosetta code: Split an array into chunks

by LanX (Saint)
on Oct 22, 2021 at 17:45 UTC ( [id://11137893]=note: print w/replies, xml ) Need Help??


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

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11137893]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-18 03:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found