假设我在Perl中有如下的数组:
@names = ("one", "two", "three", "four", "five", "six");
Run Code Online (Sandbox Code Playgroud)
我想在预定义大小的子数组("块")中循环遍历此数组.更具体地说,我想有一个变量,例如@chunk
在我的循环中,在每次迭代中保存相应的子数组:
for ? {
say @chunk;
}
Run Code Online (Sandbox Code Playgroud)
例如,如果我使用2
我的子数组/块大小,我们将迭代3次,并将@chunk
在以下内容中保持以下值:
("one", "two")
("three", "four")
("five", "six")
Run Code Online (Sandbox Code Playgroud)
如果我使用4
我的块大小,它将只迭代两次,@chunk
并将保持:
("one", "two", "three", "four")
("five", "six") # Only two items left, so the last chunk is of size 2
Run Code Online (Sandbox Code Playgroud)
在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";
}
Run Code Online (Sandbox Code Playgroud)
要更改"块"大小,只需将第一个参数更改为natatime
:
# Chunks of 4
my $it = natatime 4, @names;
Run Code Online (Sandbox Code Playgroud)