package Cycle; use warnings; require Exporter; @ISA = qw/Exporter/; @EXPORT = qw/cycle MC_cycle/; use strict; use Carp; sub cycle { # based on Ovid's algorithm my $toggle = shift; my @items = @_; unless ($toggle =~ /^\d+$/ and $toggle != 0 and @items) { my $me = (caller(0))[3]; confess "Hey stupid, you are supposed to call me like this:\n", "\t$me(positive_integer, some_list)\nNot like this:\n"; } my $count = 0; my $index = -1; return sub { $index++ if $count++ % $toggle == 0; $index = 0 if $index == @items; $items[$index]; } } sub MC_cycle { # based on MeowChow's algorithm my ($repeat, @items, $index) = @_; return sub { $items[ int ($index++ / $repeat) % @items ]; } } __END__ #### # case 1: using MC_cycle(0, @colors); [jandrew:~]$ perl foo.pl Illegal division by zero at Cycle.pm line 29. # case 2: using cycle(0, @colors); [jandrew:~]$ perl foo.pl Hey stupid, you are supposed to call me like this: Cycle::cycle(positive_integer, some_list) Not like this: Cycle::cycle(0, 'red', 'white', 'blue') called at foo.pl line 6