Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - Splitting an array, and looping through its sub-arrays

Tags:

arrays

perl

Say I have an array like the following in Perl:

@names = ("one", "two", "three", "four", "five", "six");

I would like to loop through this array in sub-arrays ("chunks") of pre-defined size. More specifically, I would like to have a variable, e.g. @chunk within my loop that holds the corresponding sub-array in each iteration:

for ? {
   say @chunk;
}

For example, if I use 2 as my sub-array/chunk size, we would iterate 3 times, and @chunk would hold the following values across the :

("one", "two")
("three", "four")
("five", "six")

If I use 4 as my chunk size, it would iterate only twice, and @chunk would hold:

("one", "two", "three", "four")
("five", "six") # Only two items left, so the last chunk is of size 2

Are there any built-ins/libraries to do this easily in Perl?

like image 692
Josh Avatar asked Dec 01 '25 05:12

Josh


1 Answers

You can do this with natatime (read N at a time) from List::MoreUtils:

my @names = qw(one two three four five six);

# Chunks of 3
my $it = natatime 3, @names;

while (my @vals = $it->())
{
    print "@vals\n";
}

To change the "chunk" size, simply change the first parameter to natatime:

# Chunks of 4
my $it = natatime 4, @names;
like image 65
ThisSuitIsBlackNot Avatar answered Dec 03 '25 20:12

ThisSuitIsBlackNot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!