arrays - 如何使数组无限循环?

标签 arrays perl loops infinite-loop

我有一个名字列表:

@names = qw(John Peter Michael);

我想从中获取 2 个值,所以我得到了 John 和 Peter。如果我想再拿两个 - 我得到迈克尔和约翰。还有 1 个 - 彼得。还有 3 个 - Michael John 和 Peter,等等。

我已经开始编写一个子例程,其中将设置和记住全局索引 ID,并且一旦达到数组的标量限制就会将自身重置为零,但后来我在某处读到 Perl 数组“记住”它们的位置被循环了。

这是真的还是我误解了什么?有没有一种方法可以轻松完成我的任务?

最佳答案

推出自己的迭代器并不难,但 perlfaq4是否满足您的需求:


How do I handle circular lists?

(contributed by brian d foy)

If you want to cycle through an array endlessly, you can increment the index modulo the number of elements in the array:

my @array = qw( a b c );
my $i = 0;
while( 1 ) {
    print $array[ $i++ % @array ], "\n";
    last if $i > 20;
} 

You can also use Tie::Cycle to use a scalar that always has the next element of the circular array:

use Tie::Cycle;
tie my $cycle, 'Tie::Cycle', [ qw( FFFFFF 000000 FFFF00 ) ];
print $cycle; # FFFFFF
print $cycle; # 000000
print $cycle; # FFFF00

The Array::Iterator::Circular creates an iterator object for circular arrays:

use Array::Iterator::Circular;
my $color_iterator = Array::Iterator::Circular->new(
    qw(red green blue orange)
    );
foreach ( 1 .. 20 ) {
    print $color_iterator->next, "\n";
}

自己动手制作的品种

子程序非常简单(在下面的代码中实现为circularize)。 $i 的值保留在 $colors 的作用域中,因此不需要状态变量:

sub circularize {
  my @array = @_;
  my $i = 0;
  return sub { $array[ $i++ % @array ] }
}

my $colors = circularize( qw( red blue orange purple ) ); # Initialize

print $colors->(), "\n" for 1 .. 14; # Use

关于arrays - 如何使数组无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48257595/

相关文章:

arrays - 使用 int 数组创建一副带有面孔和花色的纸牌

具有不同元素的 PHP 数组(如 Python 集合)

perl - SELECT DISTINCT 是否适用于 Perl 的 DBD::CSV?

perl - 在 shell 命令中插入 perl 变量

linux - app->start之后怎么办;在 Perl 的 Mojolicious websocket 中

c - GCC 5.1 循环展开

javascript - 使用 'for' 循环合并两个排序数组...如何在循环结束时阻止 'i' 增加

php - 按 3 个值对多维数组进行排序,或按值将数组拆分为 3 个数组

javascript - 使用 Javascript 向后循环 XML

arrays - Array.new(10, & :next) in ruby 下面是什么