User Input

Since not everyone remembers the hex code for each character in ASCII, a CGI program that encodes strings might be handy. This also makes for a good first example of user input. This program will start getting more complex than the other examples, using subroutines will allow you to create re-usable chunks of code for new CGI programs. While Perl does provide facilities for creating packages and libraries of functions, these examples will just use in line subroutines for simplicity.

This example program does the following:

  1. Parse the form input
  2. Output the static HTML content of the page
  3. If parameter values have been set by a previous execution of the program, process the input and display the program output.

Sometimes you will want to use a static HTML page for a form, and have it invoke a CGI via the <FORM ACTION=URL> specifier, and other times you may want to output the form directly from the CGI. I will use two versions of the example, one will use a separate .html and .cgi files. The other will display both the form and the output all in one program.

There are advantages to each technique for where the HTML for static content and forms is stored and displayed from. An advantage of embedding the static data and forms within a script is that the form variables are located close to the code that uses it, which makes for more easily documented and modified code and forms. By including the forms in the code, you also have fewer files to maintain. Plus you have more control over the content of a page when the form is in the code. It would be more difficult to have a form and the output of the program on the same output page if the forms were in a separate file.

Putting static HTML and forms in separate files can also have advantages though. You can point multiple static pages at the same CGI program, giving different interfaces to the same program. A complex page might also be more easily constructed using a WYSIWYG HTML editor than by hand coding it within the program.

Next Previous Examples

Copyright 2001 - Andy Welter