Perl中迭代循环并提取对或三元组的最佳方法是什么
我有一个平面坐标数组,我想迭代和提取 x 和 y 坐标对。相同的逻辑可以应用于 RGB 颜色的三元组。这是我到目前为止所拥有的,但它并没有感觉超级灵活或优雅。
my @coords = qw(1 5 2 6 3 8 6 12 7 5);
for (my $i = 0; $i < @coords; $i += 2) {
my $x = $coords[$i];
my $y = $coords[$i+1];
print "$x, $yn";
}
必须有更好的方法来做到这一点吗?
回答
模块List::MoreUtils有natatime(n-at-a-time)
use List::MoreUtils qw(natatime);
my @ary = 1..12;
my $it = natatime 3, @ary; # iterator
while (my @triplet = $it->()) { say "@triplet" }