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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With