O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Formatting Lists and Tables with HTML Shortcuts

Problem

You have several lists and tables to generate and would like helper functions to make these easier to output.

Solution

The CGI module provides HTML helper functions which, when passed array references, apply themselves to each element of the referenced array:

print ol( li([ qw(red blue green)]) );

                  <OL><LI>red</LI> <LI>blue</LI> <LI>green</LI></OL>
@names = qw(Larry Moe Curly);
print ul( li({ -TYPE => "disc" }, \@names) );

                  <UL><LI TYPE="disc" >Larry</LI> <LI TYPE="disc">Moe</LI> 
               
                      <LI TYPE="disc" >Curly</LI></UL>

Discussion

The distributive behavior of the HTML generating functions in CGI.pm can significantly simplify generation of lists and tables. Passed a simple string, they just produce HTML for that string. But passed an array reference, they work on all those strings.

print li("alpha");

                      <LI>alpha</LI>
print li( [ "alpha", "omega"] );

                      <LI>alpha</LI> <LI>omega</LI>

The shortcut functions for lists will be loaded when you use the :standard import tag, but you need to ask for :html3 explicitly to get helper functions for working with tables. There’s also a conflict between the <TR> tag, which would normally make a tr() function, and Perl’s built-in tr/// operator. Therefore, to make a table row, use the Tr() function.

This example generates an HTML table starting with a hash of arrays. The keys will be the row headers, and the array of values will be the columns.

use CGI qw(:standard :html3); %hash = ( "Wisconsin" => [ "Superior", ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required