解决方法
您可以使用
List::MoreUtils::natatime.从文档:
my @x = ('a' .. 'g'); my $it = natatime 3,@x; while (my @vals = $it->()) { print "@vals\n"; }
natatime在XS中实现,因此您应该更喜欢它以提高效率.仅用于说明目的,以下是如何在Perl中实现三元素迭代器生成器:
#!/usr/bin/perl use strict; use warnings; my @v = ('a' .. 'z' ); my $it = make_3it(\@v); while ( my @tuple = $it->() ) { print "@tuple\n"; } sub make_3it { my ($arr) = @_; { my $lower = 0; return sub { return unless $lower < @$arr; my $upper = $lower + 2; @$arr > $upper or $upper = $#$arr; my @ret = @$arr[$lower .. $upper]; $lower = $upper + 1; return @ret; } } }