Passing Values to a CGI script on the Command Line

Capturing a Single Parameter

CGI scripts often process data that they receive from an HTML form, for example. Such data is passed to the script as a name/value pair, separated by and equal sign:

name=value
print_this='Hello, world!'
num=6

Since CGI scripts run in a web server and error messages are logged in the web server's error log and not returned to the browser, it is a good idea to test the script on the command line before uploading it to the server.

Name/value pairs can be passed to the CGI script as command line parameters. First, however, write the CGI script. Let us assume the script is supposed to accept a parameter named 'message' and then print the parameter's value. The script might look as follows:

#!/usr/local/bin/perl

use CGI qw(:standard); # import the CGI module

$q       = new CGI;    # instantiate the CGI object

$message = $q->param('message'); # look for the parameter by name;
                                 # if it exists in the parameter list 
                                 # passed to the script, it will have a value

                                 
print "Content-type: text/html\n\n"; # print the HTTP header

print "$message\n";

Now, save the script as cgi_test_1.pl. Being in the same directory as the script, run it on the command line as follows:


perl cgi_test_1.pl message="Hello, CGI!"

Command line parameters are broken up ('tokenized') on white space, and each one is passed to the script as a separate parameter. Consequently, there may be no space between name and value, or the value cannot be retrieved by the script. Correspondingly, if the value contains white space, it must be placed in quotation marks.

The script should produce the following output:

Content-type: text/html

Hello, CGI!

If so, the CGI script work, and you can either proceed and expand the script or upload it to the server and work on the HTML output.

Capturing a Multiple Parameters

Multiple parameters can also be entered on the command line. The following script expects three input parameters:

#!/usr/local/bin/perl

use CGI qw(:standard); # import the CGI module

$q       = new CGI;    # instantiate the CGI object

$message = $q->param('message'); # first parameter
$from    = $q->param('from');    # second parameter
$to      = $q->param('to');      # third parameter

print "Content-type: text/html\n\n"; # print the HTTP header

print "Message from $from to $to:\n";
print "$message\n";

Running this script with the following input


cgi_test_2.pl from=Don to=Paula message="Meet me a 5:00 at the C-Shop."

should produce this output


Content-type: text/html

Message from Don to Paula:
Meet me a 5:00 at the C-Shop.