I got tired of doing this all the time, so I created Tie::Cycle. Every time I use the tied scalar, it advances itself along its possible values:
use Tie::Cycle;
tie my $cycle, 'Tie::Cycle', [ qw( even odd ) ];
foreach my $row ( 0 .. 6 )
{
print qq|<tr class="$cycle">...</tr>\n|;
}
In the output, it flip flops between "odd" and "even".
<tr class="even">...</tr>
<tr class="odd">...</tr>
<tr class="even">...</tr>
<tr class="odd">...</tr>
<tr class="even">...</tr>
<tr class="odd">...</tr>
<tr class="even">...</tr>
It gets better when you want to cycle through more values. Just add them to the call to tie:
use Tie::Cycle;
tie my $cycle, 'Tie::Cycle', [ qw( red white blue ) ];
foreach my $row ( 0 .. 6 )
{
print qq|<tr class="$cycle">...</tr>\n|;
}