red red white white blue blue red red white white
Update: Yeah, I changed the sub name while I was posting it. Oops! Also, the comments about my second sanity check (array ref) are correct in that my error message doesn't match the actual check. My thought was that the check would simultaneously catch whether or not it was an array and whether it would have more than zero elements. So much for trying to golf validation :)
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 ]; } }
In reply to Simple Rotation by Ovid
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |