A quick and easy way to toggle between two values
(This is based on a friend's code, which was based on
merlyn's code in a
Web Techniques magazine article
in January 1999.)
# In the configuration section...
my @Toggles = ('on', 'off');
# In some loop in the code...
$Toggles[$flip = !$flip]
I use this all the time, usually for background colors:
my @BGColors = ('#dddddd', '#ffffff');
for (1..10){ # As you loop through a database query result or somethin
+g
print qq{
<tr bgcolor="$BGColors[$flip = !$flip]">
<td>$_</td>
</tr>
};
}
Voila!
An easily configured, pretty-to-behold alternating
background color.
Notes:
- It's "just" a variable, so it interpolates well (a
ternary operator or function call must happen outside
quotes, or in @{[ ]} )
- You can "toggle between" more than 2 values like this:
- initialize $flip to -1 somewhere before your loop
- use preincrement and the modulus operator:
(see below for full example)
$Colors[$flip = ++$flip % 4];
# To cycle through any number of elements...
my @Cheers = ('hip', 'hip', 'hoo', 'ray');
my $flip = -1;
for (1..12){
print "$Cheers[$flip = ++$flip % 4]\n";
}
Enjoy!
Russ
In reply to Flipper
by Russ
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.