如何在Perl foreach循环中一次读取两个项目? [英] How do I read two items at a time in a Perl foreach loop?
问题描述
我正在寻找的东西是这样的:
What I'm looking for is something like:
@list = qw(1 2 3 4 5 6);
foreach (@list) {
#perl magic goes here
print "i: $i, j:$j\n";
}
返回:
i:1, j:2
i:3, j:4
i:5, j:6
为响应下面的一个很好的建议,我需要指定此脚本将在其他人的构建服务器上运行,并且不允许我使用CPAN中的任何模块.仅限标准Perl.
In response to a very good suggestion below, I need to specify that this script will run on someone else's build server, and I'm not allowed to use any modules from CPAN. Standard Perl only.
推荐答案
I believe the proper way to do this is to use natatime, from List::MoreUtils:
来自文档:
natatime阻止列表
natatime BLOCK LIST
创建一个数组迭代器,用于循环遍历$n
个项目的大块数组
一次. (一次n
,明白吗?).一个例子可能更好
比我无法用言语表达的解释.
Creates an array iterator, for looping over an array in chunks of $n
items
at a time. (n
at a time, get it?). An example is probably a better
explanation than I could give in words.
示例:
my @x = ('a' .. 'g');
my $it = natatime 3, @x;
while (my @vals = $it->())
{
print "@vals\n";
}
此打印
a b c
d e f
g
sub natatime ($@)
{
my $n = shift;
my @list = @_;
return sub
{
return splice @list, 0, $n;
}
}
这篇关于如何在Perl foreach循环中一次读取两个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!