我需要一个无限循环进入有限数组...
示例:
@name = ('John', 'Helen', 'Dave');
1=John
2=Helen
3=Dave
4=John
5=Helen
6=Dave
7=John
8=Helen
9=Dave
...etc
有可能吗?
感谢
答案 0 :(得分:4)
我不知道为什么有人会这样做,但这会做你想要的:
my $i=0;
my $cnt=1;
my @name = ('John', 'Helen', 'Dave');
while($i<scalar (@name )){
print $cnt."".$name[$i];
$i++;
$cnt++;
$i=$i==scalar(@name)?0:$i;
}
答案 1 :(得分:4)
听起来好像你需要使用模数大小的索引号索引有限数组:
foreach my $i (1..100) { printf "%d=%s\n", $i, $name[$i % scalar(@name)]; }
my @dow = ( 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' );
print $dow[7 % scalar(@dow)], "\n";
print $dow[125 % scalar(@dow)], "\n";
等
答案 2 :(得分:1)
为了好玩,这会呈现一个“无限”大量重复值(同时只存储每个值的一个副本)。
use InfinitelyLoopingArray qw( );
tie my @dow_lookup, InfinitelyLoopingArray::,
qw( Sun Mon Tue Wed Thu Fri Sat );
printf "%3d %s\n", $_, $dow_lookup[$_]
for 0..9, 125;
InfinitelyLoopingArray.pm
包含的位置:
package InfinitelyLoopingArray;
use strict;
use warnings;
use Carp qw( croak );
sub TIEARRAY {
my $class = shift;
return bless([ @_ ], $class);
}
sub FETCHSIZE {
# Largest supported array index.
# Currently 2**31-1 or 2**63-1 depending on the build.
return unpack('J', pack('j', -1)) >> 1;
}
sub FETCH {
my ($self, $idx) = @_;
croak "Negative indexes not supported" if $idx < 0;
return $self->[$idx % @$self];
}
sub new {
tie my @array, @_;
return \@array;
}
1;
答案 3 :(得分:0)
许多答案 - 再多一次
my(@names) = ('John', 'Helen', 'Dave');
my $cnt;
while(1) {
print ++$cnt, "=$_\n" for (@names);
}
希望,这足够无限...... :) /至少在$ cnt是overlfow /
时