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", ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.