Article

Embedding Perl Into Web Pages

Page: 1 2 3 4 5 6 7 8 9 10 11

A Third Longer Example

As another example of using Apache::ASP, we again illustrate the use of the telephone book lookup form. As before, the data is assumed to be in /usr/local/data/phone.txt, with one entry per line containing the name and phone number of a person, separated by the # symbol. We will split this application across the usual four files – a master file, phone.html, the form itself, form.html, a lookup script, which gathers the data, lookup.html, and a script to print out the results, print_it.html. All files are to be placed in the directory specified by the /asp location in httpd.conf. We will also illustrate the use of cookies in this example for saving session data across invocations of the script.

The master file, phone.html, consists of:

#!/usr/bin/perl asp            
<!--#include file=header.inc-->            
<H3>Phone book example</H3>            
<% use CGI qw(:all);            
my $name = $Request->Form('name') || '';            
if (! $name ) {          
   $Response->Include("form.html");            
}            
else {          
   $Response->Cookies('name' => $name);          
   $Response->Include("lookup.html", $name);            
}            
%>            
<!--#include file=footer.inc-->

We begin here by including the header.inc file (as in the previous example), and then pull in the CGI.pm module. We then check, through the use of $Request->Form('name'), if a value has been entered for the name parameter. If it hasn't, we print out the form contained in the include file form.html. If a value has been entered, we set a cookie via $Response->Cookies('name' => $name) to save this value across sessions, and include the file lookup.html, which will query the database and print out the results. Note how we pass to this file the variable $name through the $Response->Include("lookup.html", $name) call. Finally we include the footer footer.inc. The file form.html used to print out the form by which the user enters the query is given by:

<%=start_form %>            
<TABLE><TR>            
<TD>Please enter the name:</TD>            
<TD>            
<%          
   print textfield(-name => 'name', size => 30,          
      -value => $Request->Cookies('name'));            
%>            
</TD>            
</TR><TR>            
<TD COLSPAN=2><%=submit(-value => 'Search!') %> </TD>            
</TR></TABLE>            
<%=end_form %>

This, and later files, uses the methods of the CGI.pm module to print out various HTML tags. Note the use of $Request->Cookies('name')) to retrieve the value of name in the cookie (if it has been set) and use this value as the default for the textfield box in which the user enters the query.

When the user enters a value and submits the data, the file lookup.html will be called:

<%          
   my $name = shift;          
   my %match;          
   open (PHONE, "/usr/local/data/phone.txt")          
      or die "Cannot open phone.txt: $!";          
   while (<PHONE>) {          
      my @a = split /#/, $_;          
      next unless $a[0] =~ /$name/;          
      $match{$a[0]} = $a[1];          
   }          
   close (PHONE);          
   $Response->Include("print_it.html", (\%match, $name));            
%>

The script first captures the $name variable passed to it in the master file. It then opens up the database file and cycles through the entries, saving those that match the search criteria in the hash %match. After the results are obtained, the database file is closed and a file, print_it.html, is included that will print out the results (note that a reference to the %match hash and the original query term $name are passed to this file through the $Response->Include("print_it.html", (\%match, $name)) call). The print_it.html file is as follows:

<%          
   my ($match, $name) = @_;          
   my @names = sort keys %$match;          
   my $num = @names;          
   if ($num > 0) {          
      printf("<B>%d</B> match%s for &quot;<B>%s</B>&quot;            
      %s found:",          
         $num, ($num > 1 ? 'es' : ''), $name, ($num == 1 ? 'was'          
         : 'were') );            
%>          
   <TABLE WIDTH="40%">          
   <TR><TH ALIGN="LEFT">Name</TH>          
   <TH ALIGN="LEFT">Number<TH></TR>          
   <TR><TD COLSPAN=2><HR></TR>            
<%          
   foreach (@names) {            
%>          
      <TR>          
      <TD ALIGN="LEFT"><%=$_%></TD>          
      <TD ALIGN="LEFT"><%=$match->{$_}%></TD>          
      </TR>            
<%  } %>          
   <TR><TD COLSPAN=2><HR></TR>          
   </TABLE>            
<% }          
   else {          
%>          
   Sorry – nothing matched &quot;<B><%=$name%></B>&quot;.            
<% }          
%>          
   Try <A HREF="<%=url%>">another search</A>.

In this file we first capture the variables passed into it from lookup.html. We then set $num equal to the number of successful matches obtained. If there were any, we print out the results in a table, or otherwise we report that no successful matches were obtained. Finally, at the bottom of this page we provide a link back to the original script through the url function of the CGI.pm module.

Screenshots of this application, called through http://localhost/asp/phone.html are similar to the previous ones, so will not be repeated here.

As was done with Mason and Embperl, these examples are meant just to show the basic usage of Apache::ASP. For more complex examples, again including some of interacting with databases and of handling form data and sessions, refer to the web site at http://www.apache-asp.org/ and also to the examples contained within the source distribution. Also, in the next chapter we look at how to embed Perlscript into Active Server Pages on an NT-based machine. Many of the methods applied there will be relevant to Apache::ASP also.

Summary

Although the examples used in this chapter were relatively short, their modularization illustrates some fundamental advantages present in this approach to constructing web pages. For example, for the phone book lookup program, in order to change the appearance of the printed results, only the print_it.html file needs to be modified. Or, if at some later time one wished to use a database rather than a text file (for example, MySQL), then only the file lookup.html need be changed to query the database and return the results.

As a short summary, we have covered various ways of embedding Perl into web pages. We have looked at templates, and used two modules, HTML::Template and Template. We have also looked at two simple examples involving environment variables and a phone book lookup program using three modules: HTML::Mason, HTML::Embperl and Apache::ASP.

Like the question of the best editor, and indeed as is a general principle of Perl, the different modules have advantages in given situations, and which one to use is often a matter of personal taste, preference, and familiarity.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links

Rate This Article

  • 1
    Poor
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
    Great

Post A Comment

You need to be a member of the SitePoint Forums to comment on this post. Sign Up

Already a member? Post using your SitePoint Forums account: