Embperl can generate one- or two-dimensional tables dynamically with the use of $row and/or $col. If either $row or $col (or $cnt) is used within a <table>, Embperl repeats the text between <table> and </table> as long as the expression that includes $row/$col does not evaluate to undef.
For instance, if a program has this code:
[- @nums = (1..5); -] <table> <tr><td>[+ $nums[$row] +]</td></tr> </table>
this means start the table and then use $row to loop through @nums, one element at a time. And because it is $row, each element is treated as a row, so it repeats <tr><td> ... </td></tr>. Therefore, this is the result of this code:
<table> <tr><td>1</td></tr> <tr><td>2</td></tr> <tr><td>3</td></tr> <tr><td>4</td></tr> <tr><td>5</td></tr> </table>
Changing the code to this:
[- @nums = (1..5); -] <table> <tr><td>[+ $nums[$col] +]</td></tr> </table>
loops through @nums, and because we use $col, each element is treated as a column, so it repeats <td> ... </td>. Therefore, this is the result of this code:
<table> <tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr> </table>
Cool HTML table magic!
As an example, we display the environment variables in a table. First, we show how the table might be built without the magic and then how more magic makes life better. This code can be found in /var/wwwl/embperl/rowcoll:
<l> <head> <title>Using $row and $col</title> </head> <body bgcolor="#ffffff"> <h1>Using a <tt>foreach</tt></h1> <table border="1"> [# loop through the sorted keys of %ENV, #] [# printing the keys and their values #] [$ foreach $key (sort keys %ENV) $] <tr><th> [+ $key +] </th><td> [+ $ENV{$key} +] </td></tr> [$ endforeach $] </table> <h1>Using the Magical <tt>$row</tt> and <tt>$col</tt></h1> [# grab the sorted keys of %ENV, put them in @k #] [# then, define one row in the table, and $row will #] [# magically take on the values of the indices of @k #] [- @k = sort keys %ENV -] <table border="1"> <tr><th> [+ $k[$row] +] </th><td> [+ $ENV{$k[$row]} +] </td></tr> </table> </body> <l>
Try this program by going to one of these URLs: http://localhost/embperl/rowcoll or www.opensourcewebbook.com/embperl/rowcoll. You should see something that resembles Figure 10.6.