Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things


by Russ (Deacon)
on May 20, 2000 at 06:20 UTC ( #13834=snippet: print w/replies, xml ) Need Help??
Description: 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
  print qq{
    <tr bgcolor="$BGColors[$flip = !$flip]">

An easily configured, pretty-to-behold alternating background color.


  • 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";


Replies are listed 'Best First'.
RE: Flipper
by mdillon (Priest) on May 20, 2000 at 06:38 UTC
    for the simple on/off case, you can also use XOR:
    my @Toggles = qw(on off); $Toggles[$flip^=1];
      Ooooooh. Very nice! Hadn't seen that.
RE: Flipper
by gregorovius (Friar) on May 21, 2000 at 05:18 UTC
    You can use Tie::FlipFlop for the same purpose. Here's the synopsis from the perldoc document:
    use Tie::FlipFlop; tie my $flipflop => Tie::FlipFlop => qw /Red Green/; print $flipflop; # Prints 'Red'. print $flipflop; # Prints 'Green'. print $flipflop; # Prints 'Red'.
    It's probably too much for such a simple function but frees you from keeping the $flip variable around.

    You can use Tie::Counter in the same fashion to rotate through more than two elements.
RE: Flipper
by merlyn (Sage) on May 21, 2000 at 04:12 UTC
      Interesting idea about throwing away the result of ++. I disagree...

      But, why would we care?

      I settled on this code because I believe it specifically addresses the large-scale operation we want, which is increment $flip each time, but reset it to zero when it gets to 4. As opposed to: set $flip according to the following formula...

      Each time through, we want to increase the value of $flip by 1. The idiomatic way to say that is ++$flip.

      What, fundamentally, is the difference between

      $flip = ++$flip % 4
      $flip = ($flip + 1) % 4
      (except being three characters longer) when the entire point is to increase $flip by 1?

      I guess my question is: why do you think I am throwing away a result which you only accomplish differently? "++" vs. "+ 1" -- they both add one to the value of $flip. See below for the readability benefits of using ++ to add one to a variable.

      I like the shorter (by two characters, but hey...) version

      ($flip += 1) %= 4
      but by your argument, you shouldn't like it, either, since it increments $flip, just to "throw the result of the += away." I don't understand your objection.
      It is also much closer to being needlessly obfuscated, with all the obvious negatives... (though my coworkers might be shocked to hear that I don't prefer obfuscation :-)

      I'm sure you considered, as I did:

      for (1..12){ print "$Cheers[++$flip % 4]\n"; }
      and rejected it because we want to emphasize the purpose of $flip, which is to cycle among the elements of the array. We assign to $flip to keep its value within the legal bounds. By this we make it obvious (at a glance) to the poor programmer who comes behind us that $flip will only hold values between (in this example) 0 and 3, because those are the only values we want.

      I would argue that the preincrement adds a huge "obviousness" value for the aforementioned fellow programmer. ++$flip triggers an immediate (subconscious?) understanding of our intent. Similarly, <nobr>$flip = ++$flip % 4</nobr> is, I believe, immediately obvious in a way that <nobr>($flip += 1) %= 4</nobr> can never be. <nobr>($flip + 1)</nobr> is plain in its intent (make $flip increase by one each time), but not as plain as ++$flip.


        > I guess my question is: why do you think I am throwing
        > away a result which you only accomplish differently?
        > "++" vs. "+ 1" -- they both add one to the value
        > of $flip.

        Um, no, they do not. Saying
        $flip + 1;
        does not change in any way the scalar referred to by $flip, while "++$flip" does. Simple as that.

        What, fundamentally, is the difference between 
          $flip = ++$flip % 4
          $flip = ($flip + 1) % 4
        The first changes the value of $flip twice, the second, only once. In the first one, the computer is saying:
        1. Increase the value of $flip by one
        2. Modulo 4 it
        3. Assign the result into $flip
        1. Compute the value of $flip + 1
        2. Modulo for that (temporary) value
        3. Assign the result into $flip
Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: snippet [id://13834]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2022-08-08 22:03 GMT
Find Nodes?
    Voting Booth?

    No recent polls found