use warnings; use strict; my @colors = qw/ red white blue /; my $rotate = cycle( 2, \@colors ); for ( 1..10 ) { print &$rotate . "\n"; } sub cycle { my ( $toggle, $items ) = @_; my $error = ''; if ( $toggle !~ /^\d+$/ or $toggle == 0 ) { $error = "The first argument to &alternate must be a positive integer: $toggle\n"; } if ( ! @$items ) { $error .= "The second argument to &alternate must be an array reference."; } die $error if $error; my $count = 0; my $index = -1; return sub { $index += 1 if $count++ % $toggle == 0; $index = 0 if $index == @$items; $items->[ $index ]; } }