This is posted in response to qball's question about alternating row colors. The sub &cycle (yes, I know there is a Tie::Cycle module) takes two arguments. The first is the number of times each element gets returned prior to moving to the next element. The second argument is a reference to an array that contains the elements to cycle through. The code below prints:
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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.