假设我在 Perl 中有一个如下所示的数组:
@names = ("one", "two", "three", "four", "five", "six");
我想以预定义大小的子数组(“ block ”)循环遍历该数组。更具体地说,我想要一个变量,例如我的循环中的 @chunk
在每次迭代中保存相应的子数组:
for ? {
say @chunk;
}
例如,如果我使用 2
作为子数组/ block 大小,我们将迭代 3 次,并且 @chunk
将保持以下值:
("one", "two")
("three", "four")
("five", "six")
如果我使用 4
作为 block 大小,它只会迭代两次,并且 @chunk
将保留:
("one", "two", "three", "four")
("five", "six") # Only two items left, so the last chunk is of size 2
是否有任何内置程序/库可以在 Perl 中轻松完成此操作?
最佳答案
您可以使用 List::MoreUtils 中的 natatime
(一次读取 N)来执行此操作:
my @names = qw(one two three four five six);
# Chunks of 3
my $it = natatime 3, @names;
while (my @vals = $it->())
{
print "@vals\n";
}
要更改“ block ”大小,只需将第一个参数更改为natatime
:
# Chunks of 4
my $it = natatime 4, @names;
关于arrays - Perl - 分割数组并循环其子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20338497/