The Perl CGI Module
The Perl CGI module has some helpful functions to simplify
generating common snippets of HTML. We can enable all these by
modifying our use
statement to:
use CGI ':all'
We can then
generate HTML elements by calling the corresponding function. For
example, we can include text within a level-one heading tag pair
(<h1>
)
by writing text
</h1>h1("text")
.
Many of these functions take attributes that are reflected in
the generated HTML. For example, to generate the tag <th align="LEFT" bgcolor="SKYBLUE">
,
we would write:
th({-align=>"LEFT", -bgcolor=>"SKYBLUE"}, $Name).
Example 18-3 rewrites our our previous example using CGI functions.
Example 18-3. The CGI Animal list script rewritten with CGI functions
#!/usr/bin/perl use strict; # Connect to the MySQL server, run the query, store the result use DBI; my $dbh=DBI->connect("DBI:mysql:host=localhost;database=AnimalDB", "the_username", "the_password", {PrintError=>0, RaiseError=>1}); my $results = $dbh->selectall_hashref('SELECT * FROM Animals', 'Name'); $dbh->disconnect(); # Prepare and display the results in HTML format use CGI ':all'; my @AnimalsDataArray; foreach my $Name (keys %$results) { my $AnimalsDataArrayRow = th({-align=>"LEFT", -bgcolor=>"SKYBLUE"}, $Name). td({-bgcolor=>"PINK"}, [$results->{$Name}->{Count}]); push @AnimalsDataArray, $AnimalsDataArrayRow; } my $result= header(-type=>"text/html", -charset=>'UTF-8'). start_html(-title=>"List of Animals", -encoding => 'UTF-8'). h1("Pet roll call"). table( {-border=>'true'}, ...
Get Learning MySQL 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.