Code Snippet: Table Rows with Alternating Colors
You're probably thinking, I know how to do that! All I need to do is put
different background colors in the <tr> tag for each row.
And
you're right!
But what if you don't know ahead of time how many rows are going to be in your table? I run into this all the time. I want to print out a table using information from a database, so I am using a while loop to print each row. How does the loop know which background color to print next?
The loop has to think like this, First I'm going to pick blue, then I'm
going to pick white, then I'm going to pick blue, then white, ... .
There is an operation called "modulo" [1], which can help here.
Unfortunately, this is not in Perl's vocabulary, so we'll have to construct
it from the Perl integer function.
If we call the row number $j , then the modulo function that will give us alternating numbers, $jmod2 , is
$jmod2 = ( $j/2 - int ( $j/2 ) ) * 2
Try it out! Put in $j = 1, 2, 3, 4, ... , and you should get $jmod2 = 1, 0, 1, 0, ... .
Now, just make an array containing the two colors, and the output of the $jmod2 function gives the index of the array.
Here's the Perl script:
1 $j = 0;
2 @color = ("#FFF", "#0CC");
3 while ($j < 4)
4 {
5 $j++;
6 $jmod2 = ( $j/2 - int ( $j/2 ) ) * 2;
7 print "<tr style='background-color:$color[$jmod2];'>\n";
8 print "<td>[ WHATEVER YOU WANT TO PRINT HERE ]</td>\n";
9 [...MAYBE SOME MORE COLUMNS HERE...]
10 print "</tr>\n";
11 }
Of course, if you want to use this to print out rows from a database, you will have to insert some database connect, prepare, and execute statements after line 2, and change line 3 to fetch a row of your database.
Update - July 20, 2006: If you don't like using the modulo operation, here's an alternate script that does the same thing in a different way. You only need to change three lines in the above code.
1) Remove line #2.
2) Substitute the following two lines for line #6:
if ($color == "#0CC") $color = "#FFF"; else $color = "#0CC";
[1] The modulo operation yields the remainder when a number is divided by the modulus. For example, 11 (mod 3) = 2 since 11 divided by 3 gives a remainder of 2. The script above uses a modulus of 2, so the only remainders possible for $jmod2 are 0 and 1.