19.7. Formatting Lists and Tables with HTML ShortcutsProblemYou have several lists and tables to generate and would like helper functions to make these easier to output. SolutionThe 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)]) ); DiscussionThe 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");
The shortcut functions for lists will be loaded when you use the 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", "Lake Geneva", "Madison" ], "Colorado" => [ "Denver", "Fort Collins", "Boulder" ], "Texas" => [ "Plano", "Austin", "Fort Stockton" ], "California" => [ "Sebastopol", "Santa Rosa", "Berkeley" ], ); $\ = "\n"; print "<TABLE> <CAPTION>Cities I Have Known</CAPTION>"; print Tr(th [qw(State Cities)]); for $k (sort keys %hash) { print Tr(th($k), td( [ sort @{$hash{$k}} ] )); } print "</TABLE>"; That generates text that looks like this:
You can produce the same output using one print statement, although it is slightly trickier, because you have to use a print table caption('Cities I have Known'), Tr(th [qw(State Cities)]), map { Tr(th($_), td( [ sort @{$hash{$_}} ] )) } sort keys %hash; This is particularly useful for formatting the results of a database query, as in Example 19.3 (see Chapter 14, Database Access ). Example 19.3: salcheck#!/usr/bin/perl # salcheck - check for salaries use DBI; use CGI qw(:standard :html3); $limit = param("LIMIT"); print header(), start_html("Salary Query"), h1("Search"), See AlsoThe documentation for the standard CGI module; Recipe 14.10 |
|