Tweet

Writing a CGI script

In this tutorial you will learn how to write a Perl CGI script.

Firstly you need to ensure that you have access to a web server (that has Perl installed), that it has cgi enabled, and that you can put your Perl script into the cgi directory.

Starting your script

    #!/usr/bin/perl
    use strict;
    use warnings;
    use CGI;

The CGI module is the easiest way to create a cgi script. While you can do all the parsing and handling headers and encoding URLs yourself, the CGI module does all this, (and much more) for you, allowing you to concentrate on the application itself.

Having imported the CGI module with the use keyword, we then create a CGI object:

    my $q = new CGI;

By convention this is nearly always $q or $query.

Starting the output

We use the CGI object to print out the HTTP header for the output:

    print $q->header;

This gives you the following HTTP header:

    Content-Type: text/html; charset=ISO-8859-1

If you need to have any extra options in your header, for example you may not want the default 'type', you can just pass them in to the header method:

    print $q->header(-type => "text/plain");

This gives you the following HTTP header:

    Content-Type: text/plain; charset=ISO-8859-1

Object Oriented or functional

You can either use the CGI object to output HTML in an object oriented fashion, or use the CGI module's functional interface.

For example, the following two code samples produce the same output.

Object oriented style:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use CGI;

    my $q = new CGI;

    print $q->header;
    print $q->start_html;
    print $q->h1("Hello World!");
    print $q->end_html;

Functional style:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use CGI qw(:standard);

    print header;
    print start_html;
    print h1("Hello World!");
    print end_html;

In this tutorial we'll be using the Object Oriented interface to the CGI module to output our HTML.

Starting your HTML

To start the HTML, you can use the start_html tag.

    print $q->start_html;

If you want to give the page a title, you can use:

    print $q->start_html("The title");

Or if you want to pass in more parameters:

    print $q->start_html(
        -title   => 'The title',
        -author  => 'becky@unisolve.com.au',
        -meta    => {keywords => 'Perl cgi tutorial'},
        -style   => {'src' => '/styles/sample.css'},
    );

When you want to end the html, just use the end_html method:

    print $q->end_html;

Tags

You can use the CGI module to print any HTML tag:

Heading tags:

    print $q->h2("Example HTML");

Paragraph tags:

    print $q->p("This page was generated using the CGI module");

Table tags:

    print $q->table(
        {-border=>1, cellpadding=>3},
        $q->Tr([
            $q->th(['One', 'Two', 'Three', 'Four']),
            $q->td(['One', 'Two', 'Three', 'Four']),
            $q->td(['Two', 'Four', 'Six', 'Eight']),
            $q->td(['Three', 'Six', 'Nine', 'Twelve']),
            $q->td(['Four', 'Eight', 'Twelve', 'Sixteen']),
        ]),
    );

Notice that we've passed an anonymous array to the th and td methods. Some CGI methods will accept either scalar variables or an array reference. When the method is passed an array reference, tags will be generated for each element in the array. For example, the following line:

    my @array = ('One', 'Two', 'Three', 'Four');
    print $q->th(\@array);

Produces the following output:

    <th>One</th><th>Two</th><th>Three</th><th>Four</th>

Lists:

    print $q->ul(
        $q->li(['very high', 'high', 'medium', 'low', 'very low']),
    );

Like table cells, you can pass a scalar or an array reference to the li method.

Function names that are different from the HTML tag name

In general, the function names you use are the same as the tag names. One thing to beware of is the capitalization of some functions. (If these functions weren't capitalized, they'd clash with Perl built-in functions of the same name):

    Accept
    Delete
    Link
    Select
    Sub
    Tr

When you use these functions, remember to capitalize the first letter.

Working example

Below is a full working example of a html page output entirely using the CGI module's Object Oriented interface.

    #!/usr/bin/perl
    use strict;
    use warnings;

    use CGI;
    # use CGI::Carp qw(fatalsToBrowser); # Uncomment for debugging

    my $q = new CGI;

    print $q->header;

    my $style = get_style();

    print $q->start_html(
        -title => "An example web page",
        -style => {-code => $style},
    );

    print $q->h2("Grandma's Lemon Cordial");

    print $q->p("Lots of Experience - I've made it once before!");

    print $q->h4("Ingredients");

    print $q->ul(
        $q->li(['water', 'sugar', 'lemon juice']),
    );

    print $q->h4("Nutrition Information");

    print $q->table(
        {-cellpadding => 3},
        $q->Tr($q->th(['Per', 'Serving', '100mL'])),
        $q->Tr($q->td(['Energy', '333kj', '133kj'])),
        $q->Tr($q->td(['Protein', '<1g', '<1g'])),
        $q->Tr($q->td(['Fat -total', '<1g', '<1g'])),
        $q->Tr($q->td(['-saturated', '<1g', '<1g'])),
        $q->Tr($q->td(['Carbohydrate -total', '15g', '6g'])),
        $q->Tr($q->td(['-sugars', '15g', '6g'])),
        $q->Tr($q->td(['sodium', '35mg', '14mg'])),
    );

    print $q->end_html;

    exit 0;

    #-------------------------------------------------------------

    sub get_style {
        my $style = <<"EOT";
        body {
            font-family: verdana, arial, sans-serif;
            bgcolor: white;
	    padding-left: 5%;
        }
        H2 {
            color: green;
            border-bottom: 1pt solid;
        }
        H4 {
            color: darkgreen;
        }
        p {
            font-variant: small-caps;
            font-weight: bold;
        }
        table {
            border: darkgreen 1pt solid;
        }
        th,td {
            border: green 1pt dashed;
        }
    EOT
        return $style;
    }

    #-------------------------------------------------------------

The output of this program can be seen here.

See Also

    perldoc CGI
    perldoc CGI::Carp
[Top]