1. Computing

Working with CGI.pm In-Depth - Creating HTML Forms

Starting and Stopping a Form

From , former About.com Guide

You can also use Perl's CGI.pm to easily create HTML forms and process their input. Let's start by taking a look at the most basic aspect of creating HTML forms with CGI.pm - starting and stopping the form. CGI.pm has two simple functions, the last of which is really just for code symmetry. They are start_form and endform.

First let's take a look at the one that is a bit pointless - endform. If we write a simple script and run the function, we can see the output. Here's the script:

 #!/usr/bin/perl -w
 
 use strict;
 use CGI qw/:standard/;
 my $cgi = new CGI;
 
 print $cgi->endform; 
And running this program will generate the following output:
 </form> 
Wow. What a waste of processing power. There's some argument that the processing power you lose is negligible, which is often the case, and that it makes the code more symmetrical. This is also true, but for my own personal preference, I like to squeeze every last bit out of my scripts. You could just as easily print '</form>';, pick whichever you like, it's your choice.

Let's spend some time on the really interesting one, start_form. First, we add a line to our script so we can print the output from the start_form command:

 print $cgi->start_form( -action => 'index.cgi' ); 
Here's the output:
 <form method="post" action="index.cgi" enctype="multipart/form-data"> 
If you're at all familiar with forms, you'll realize two things at this point. One is that you can specify the action, or where the form data is sent when it's submitted, by using the -action attribute and giving it the full path to your processing CGI. The second thing you'll see is that the default encoding type of the form is multipart/form-data - this is suitable for passing binary data (file uploads). You can control the encoding type of the form with the -enctype option.

Finally, you can use the -method option to switch between your standard, default POST method and GET. Now that you know how to create the basic form, let's move on to putting something in it.

©2013 About.com. All rights reserved.