![]() |
Hello World with CGI.pm |
||
|
Now, lets take our Hello World program and make it more sophisticated: #!/usr/bin/perl # It's always a good idea to use the strict pragma while developing # Perl code, it makes Perl warn about dangerous code use strict; # We're also going to include the CGI module, so that we can take # advantage of other programmer's efforts (One of Larry Wall's basic # tennants is that programmers are fundamentally lazy -- he's probably # right, but I can't be bothered to prove it right now) use CGI; # instantiate a new CGI object my $cgi = new CGI; # perform a single print statement, with liberal use of the perl # string concatenator "." and some CGI methods print $cgi->header . $cgi->start_html('Hello World!') . $cgi->h1('Hello World!') . $cgi->end_html; # Tell the webserver everything is fine exit (0); To see this program in action: Look familiar? If you remove the comments from the above code you will find that it is much shorter than the previous version, but it looks exactly the same. The reason for this is the CGI module (if you get an error about not finding CGI.pm, then you need to install it from CPAN), which is a native perl interface to HTTP and HTML. We first tell Perl that we want to use the CGI module with the use directive:
Then we instantiate a new CGI object for our use:
Now, we can call the many methods that the CGI object exposes:
Which is easier? Good question. Use what happens to be best at the moment, but keep in mind that CGI.pm is always updated to use the latest in HTML technologies and standards, while hand-crafted code must be hand-maintained as well. CGI.pm also provides very handy interfaces for reading and writing HTTP (form) variables, cookies and it integrates with other Perl web technologies to provide a holistic development platform. Here is the abstract for CGI.pm:
You can view the CGI module documentation by visiting the above two links, or you can consult the local documentation on your system using one of the following methods, depending on your system:
All pages written by Craig Kelley unless otherwise specified. Please use the Contact link from the menu to submit changes or suggestions. Permission is given to use this tutorial in any way you wish including re-publishing or "mirroring". The most up-to-date version of this document currently resides at http://inconnu.isu.edu/~ink/perl_cgi. This page updated: May 6, 2002 22:21 |