[logo] CGI.pm - a Perl5 CGI Library

Version 2.56, 9/13/1999, L. Stein

Abstract

This perl 5 library uses objects to create Web fill-out forms on the fly and to parse their contents. It provides a simple interface for parsing and interpreting query strings passed to CGI scripts. However, it also offers a rich set of functions for creating fill-out forms. Instead of remembering the syntax for HTML form elements, you just make a series of perl function calls. An important fringe benefit of this is that the value of the previous query is used to initialize the form, so that the state of the form is preserved from invocation to invocation.

Everything is done through a ``CGI'' object. When you create one of these objects it examines the environment for a query string, parses it, and stores the results. You can then ask the CGI object to return or modify the query values. CGI objects handle POST and GET methods correctly, and correctly distinguish between scripts called from <ISINDEX> documents and form-based documents. In fact you can debug your script from the command line without worrying about setting up environment variables.

A script to create a fill-out form that remembers its state each time it's invoked is very easy to write with CGI.pm:

#!/usr/local/bin/perl

use CGI qw(:standard);

print header;
print start_html('A Simple Example'),
    h1('A Simple Example'),
    start_form,
    "What's your name? ",textfield('name'),
    p,
    "What's the combination?",
    p,
    checkbox_group(-name=>'words',
		   -values=>['eenie','meenie','minie','moe'],
		   -defaults=>['eenie','minie']),
    p,
    "What's your favorite color? ",
    popup_menu(-name=>'color',
	       -values=>['red','green','blue','chartreuse']),
    p,
    submit,
    end_form,
    hr;

if (param()) {
    print 
	"Your name is",em(param('name')),
	p,
	"The keywords are: ",em(join(", ",param('words'))),
	p,
	"Your favorite color is ",em(param('color')),
	hr;
}
print end_html;
Select this link to try the script
More scripting examples
Source code examples from The Official Guide to CGI.pm

Contents

  • Downloading & Installation
  • Function-Oriented vs Object-Oriented Use
  • Creating a new CGI query object
  • Saving the state of the form
  • CGI Functions that Take Multiple Arguments
  • Creating the HTTP header
  • HTML shortcuts
  • Creating forms
  • Importing CGI methods
  • Retrieving CGI.pm errors
  • Debugging
  • HTTP session variables
  • HTTP Cookies
  • Support for frames
  • Support for JavaScript
  • Limited Support for Cascading Style Sheets
  • Using NPH Scripts
  • Advanced techniques
  • Subclassing CGI.pm
  • Using CGI.pm with mod_perl and FastCGI
  • Migrating from cgi-lib.pl
  • Using the File Upload Feature
  • Server Push
  • Avoiding Denial of Service Attacks
  • Using CGI.pm on non-Unix Platforms
  • The Relationship of CGI.pm to the CGI::* Modules
  • Distribution information
  • The CGI.pm Book
  • CGI.pm and the Year 2000 Problem
  • Bug Reporting and Support
  • What's new?

  • Downloading & Installation

    The current version of the software can always be downloaded from the master copy of this document maintained at http://stein.cshl.org/WWW/software/CGI/.

    This package requires perl 5.004 or higher. Earlier versions of Perl may work, but CGI.pm has not been tested with them. If you're really stuck, edit the source code to remove the line that says "require 5.004", but don't be surprised if you run into problems.

    If you are using a Unix system, you should have perl do the installation for you. Move to the directory containing CGI.pm and type the following commands:

       % perl Makefile.PL
       % make
       % make install
    
    You may need to be root to do the last step.

    This will create two new files in your Perl library. CGI.pm is the main library file. Carp.pm (in the subdirectory "CGI") contains some optional utility routines for writing nicely formatted error messages into your server logs. See the Carp.pm man page for more details.

    If you get error messages when you try to install, then you are either:

    1. Running a Windows NT or Macintosh port of Perl that doesn't have make or the MakeMaker program built into it.
    2. Have an old version of Perl. Upgrade to 5.004 or higher.
    In the former case don't panic. Here's a recipe that will work (commands are given in MS-DOS/Windows form):
      > cd CGI.pm-2.46
      > copy CGI.pm C:\Perl\lib
      > mkdir C:\Perl\lib\CGI
      > copy CGI\*.pm C:\Perl\lib\CGI
    
    Modify this recipe if your Perl library has a different location.

    For Macintosh users, just drag the file named CGI.pm into the folder where your other Perl .pm files are stored. Also drag the subfolder named "CGI".

    If you do not have sufficient privileges to install into /usr/local/lib/perl5, you can still use CGI.pm. Modify the installation recipe as follows:

       % perl Makefile.PL INSTALLDIRS=site INSTALLSITELIB=/home/your/private/dir
       % make
       % make install
    
    Replace /home/your/private/dir with the full path to the directory you want the library placed in. Now preface your CGI scripts with a preamble something like the following:
    use lib '/home/your/private/dir';
    use CGI;
    
    Be sure to replace /home/your/private/dir with the true location of CGI.pm.

    Notes on using CGI.pm in NT and other non-Unix platforms


    Function-Oriented vs Object-Oriented Use

    CGI.pm can be used in two distinct modes called function-oriented and object-oriented. In the function-oriented mode, you first import CGI functions into your script's namespace, then call these functions directly. A simple function-oriented script looks like this:
    #!/usr/local/bin/perl
    use CGI qw/:standard/;
    print header(),
          start_html(-title=>'Wow!'),
          h1('Wow!'),
          'Look Ma, no hands!',
          end_html();
    
    The use operator loads the CGI.pm definitions and imports the ":standard" set of function definitions. We then make calls to various functions such as header(), to generate the HTTP header, start_html(), to produce the top part of an HTML document, h1() to produce a level one header, and so forth.

    In addition to the standard set, there are many optional sets of less frequently used CGI functions. See Importing CGI Methods for full details.

    In the object-oriented mode, you use CGI; without specifying any functions or function sets to import. In this case, you communicate with CGI.pm via a CGI object. The object is created by a call to CGI::new() and encapsulates all the state information about the current CGI transaction, such as values of the CGI parameters passed to your script. Although more verbose, this coding style has the advantage of allowing you to create multiple CGI objects, save their state to disk or to a database, and otherwise manipulate them to achieve neat effects.

    The same script written using the object-oriented style looks like this:

    #!/usr/local/bin/perl
    use CGI;
    $q = new CGI;
    print $q->header(),
          $q->start_html(-title=>'Wow!'),
          $q->h1('Wow!'),
          'Look Ma, no hands!',
          $q->end_html();
    
    The object-oriented mode also has the advantage of consuming somewhat less memory than the function-oriented coding style. This may be of value to users of persistent Perl interpreters such as mod_perl.

    Many of the code examples below show the object-oriented coding style. Mentally translate them into the function-oriented style if you prefer.

    Creating a new CGI object

    The most basic use of CGI.pm is to get at the query parameters submitted to your script. To create a new CGI object that contains the parameters passed to your script, put the following at the top of your perl CGI programs:
        use CGI;
        $query = new CGI;
    
    In the object-oriented world of Perl 5, this code calls the new() method of the CGI class and stores a new CGI object into the variable named $query. The new() method does all the dirty work of parsing the script parameters and environment variables and stores its results in the new object. You'll now make method calls with this object to get at the parameters, generate form elements, and do other useful things.

    An alternative form of the new() method allows you to read script parameters from a previously-opened file handle:

        $query = new CGI(FILEHANDLE)
    
    The filehandle can contain a URL-encoded query string, or can be a series of newline delimited TAG=VALUE pairs. This is compatible with the save() method. This lets you save the state of a CGI script to a file and reload it later. It's also possible to save the contents of several query objects to the same file, either within a single script or over a period of time. You can then reload the multiple records into an array of query objects with something like this:
    open (IN,"test.in") || die;
    while (!eof(IN)) {
        my $q = new CGI(IN);
        push(@queries,$q);
    }
    
    You can make simple databases this way, or create a guestbook. If you're a Perl purist, you can pass a reference to the filehandle glob instead of the filehandle name. This is the "official" way to pass filehandles in Perl5:
        my $q = new CGI(\*IN);
    
    (If you don't know what I'm talking about, then you're not a Perl purist and you needn't worry about it.)

    If you are using the function-oriented interface and want to initialize CGI state from a file handle, the way to do this is with restore_parameters(). This will (re)initialize the default CGI object from the indicated file handle.

    open (IN,"test.in") || die;
    restore_parameters(IN);
    close IN;
    

    You can initialize a CGI object from an associative-array reference. Values can be either single- or multivalued:

    $query = new CGI({'dinosaur'=>'barney',
                      'song'=>'I love you',
                      'friends'=>[qw/Jessica George Nancy/]});
    
    You can initialize a CGI object by passing a URL-style query string to the new() method like this:
    $query = new CGI('dinosaur=barney&color=purple');
    
    Or you can clone a CGI object from an existing one. The parameter lists of the clone will be identical, but other fields, such as autoescaping, are not:
    $old_query = new CGI;
    $new_query = new CGI($old_query);
    

    This form also allows you to create a CGI object that is initially empty:

    $empty_query = new CGI('');
    
    See advanced techniques for more information.

    Fetching A List Of Keywords From The Query

        @keywords = $query->keywords
    
    If the script was invoked as the result of an <ISINDEX> search, the parsed keywords can be obtained with the keywords() method. This method will return the keywords as a perl array.

    Fetching The Names Of All The Parameters Passed To Your Script

        @names = $query->param
    
    If the script was invoked with a parameter list (e.g. "name1=value1&name2=value2&name3=value3"), the param() method will return the parameter names as a list. For backwards compatability, this method will work even if the script was invoked as an <ISINDEX> script: in this case there will be a single parameter name returned named 'keywords'.

    Fetching The Value(s) Of A Named Parameter

       @values = $query->param('foo');
                 -or-
       $value = $query->param('foo');
    
    Pass the param() method a single argument to fetch the value of the named parameter. If the parameter is multivalued (e.g. from multiple selections in a scrolling list), you can ask to receive an array. Otherwise the method will return a single value.

    As of version 1.50 of this library, the array of parameter names returned will be in the same order in which the browser sent them. Although this is not guaranteed to be identical to the order in which the parameters were defined in the fill-out form, this is usually the case.

    Setting The Value(s) Of A Named Parameter

       $query->param('foo','an','array','of','values');
                       -or-
       $query->param(-name=>'foo',-values=>['an','array','of','values']);
    
    This sets the value for the named parameter 'foo' to one or more values. These values will be used to initialize form elements, if you so desire. Note that this is the one way to forcibly change the value of a form field after it has previously been set.

    The second example shows an alternative "named parameter" style of function call that is accepted by most of the CGI methods. See Calling CGI functions that Take Multiple Arguments for an explanation of this style.

    Appending a Parameter

       $query->append(-name=>'foo',-values=>['yet','more','values']);
    
    This adds a value or list of values to the named parameter. The values are appended to the end of the parameter if it already exists. Otherwise the parameter is created.

    Deleting a Named Parameter Entirely

       $query->delete('foo');
    
    This deletes a named parameter entirely. This is useful when you want to reset the value of the parameter so that it isn't passed down between invocations of the script.

    Deleting all Parameters

       $query->delete_all();
    
    This deletes all the parameters and leaves you with an empty CGI object. This may be useful to restore all the defaults produced by the form element generating methods.

    Importing parameters into a namespace

       $query->import_names('R');
       print "Your name is $R::name\n"
       print "Your favorite colors are @R::colors\n";
    
    This imports all parameters into the given name space. For example, if there were parameters named 'foo1', 'foo2' and 'foo3', after executing $query->import_names('R'), the variables @R::foo1, $R::foo1, @R::foo2, $R::foo2, etc. would conveniently spring into existence. Since CGI has no way of knowing whether you expect a multi- or single-valued parameter, it creates two variables for each parameter. One is an array, and contains all the values, and the other is a scalar containing the first member of the array. Use whichever one is appropriate. For keyword (a+b+c+d) lists, the variable @R::keywords will be created.

    If you don't specify a name space, this method assumes namespace "Q".

    An optional second argument to import_names, if present and non-zero, will delete the contents of the namespace before loading it. This may be useful for environments like mod_perl in which the script does not exit after processing a request.

    Warning: do not import into namespace 'main'. This represents a major security risk, as evil people could then use this feature to redefine central variables such as @INC. CGI.pm will exit with an error if you try to do this.

    Direct Access to the Parameter List

    $q->param_fetch('address')->[1] = '1313 Mockingbird Lane';
    unshift @{$q->param_fetch(-name=>'address')},'George Munster';
    
    If you need access to the parameter list in a way that isn't covered by the methods above, you can obtain a direct reference to it by calling the param_fetch() method with the name of the parameter you want. This will return an array reference to the named parameters, which you then can manipulate in any way you like.

    You may call param_fetch() with the name of the CGI parameter, or with the -name argument, which has the same meaning as elsewhere.

    Fetching the Parameter List as a Hash

    $params = $q->Vars;
    print $params->{'address'};
    @foo = split("\0",$params->{'foo'});
    %params = $q->Vars;
    
    use CGI ':cgi-lib';
    $params = Vars;
    

    Many people want to fetch the entire parameter list as a hash in which the keys are the names of the CGI parameters, and the values are the parameters' values. The Vars() method does this. Called in a scalar context, it returns the parameter list as a tied hash reference. Changing a key changes the value of the parameter in the underlying CGI parameter list. Called in an array context, it returns the parameter list as an ordinary hash. This allows you to read the contents of the parameter list, but not to change it.

    When using this, the thing you must watch out for are multivalued CGI parameters. Because a hash cannot distinguish between scalar and array context, multivalued parameters will be returned as a packed string, separated by the "\0" (null) character. You must split this packed string in order to get at the individual values. This is the convention introduced long ago by Steve Brenner in his cgi-lib.pl module for Perl version 4.

    If you wish to use Vars() as a function, import the :cgi-lib set of function calls (also see the section on CGI-LIB compatibility).

    RETRIEVING CGI ERRORS

    Errors can occur while processing user input, particularly when processing uploaded files. When these errors occur, CGI will stop processing and return an empty parameter list. You can test for the existence and nature of errors using the cgi_error() function. The error messages are formatted as HTTP status codes. You can either incorporate the error text into an HTML page, or use it as the value of the HTTP status:

        my $error = $q->cgi_error;
        if ($error) {
    	print $q->header(-status=>$error),
    	      $q->start_html('Problems'),
                  $q->h2('Request not processed'),
    	      $q->strong($error);
            exit 0;
        }
    

    When using the function-oriented interface (see the next section), errors may only occur the first time you call param(). Be prepared for this! Table of contents


    Saving the Current State of a Form

    Saving the State to a File

       $query->save(FILEHANDLE)
    
    This writes the current query out to the file handle of your choice. The file handle must already be open and be writable, but other than that it can point to a file, a socket, a pipe, or whatever. The contents of the form are written out as TAG=VALUE pairs, which can be reloaded with the new() method at some later time. You can write out multiple queries to the same file and later read them into query objects one by one.

    If you wish to use this method from the function-oriented (non-OO) interface, the exported name for this method is save_parameters(). See advanced techniques for more information.

    Saving the State in a Self-Referencing URL

       $my_url=$query->self_url
    
    This call returns a URL that, when selected, reinvokes this script with all its state information intact. This is most useful when you want to jump around within a script-generated document using internal anchors, but don't want to disrupt the current contents of the form(s). See advanced techniques for an example.

    If you'd like to get the URL without the entire query string appended to it, use the url() method:

       $my_self=$query->url
    

    Obtaining the Script's URL

        $full_url      = $query->url();
        $full_url      = $query->url(-full=>1);  #alternative syntax
        $relative_url  = $query->url(-relative=>1);
        $absolute_url  = $query->url(-absolute=>1);
        $url_with_path = $query->url(-path_info=>1);
        $url_with_path_and_query = $query->url(-path_info=>1,-query=>1);
    
    url() returns the script's URL in a variety of formats. Called without any arguments, it returns the full form of the URL, including host name and port number
    http://your.host.com/path/to/script.cgi
    
    You can modify this format with the following named arguments:
    -absolute
    If true, produce an absolute URL, e.g.
    /path/to/script.cgi
          

    -relative
    Produce a relative URL. This is useful if you want to reinvoke your script with different parameters. For example:
        script.cgi
    

    -full
    Produce the full URL, exactly as if called without any arguments. This overrides the -relative and -absolute arguments.

    -path,-path_info
    Append the additional path information to the URL. This can be combined with -full, -absolute or -relative. -path_info is provided as a synonym.

    -query (-query_string)
    Append the query string to the URL. This can be combined with -full, -absolute or -relative. -query_string is provided as a synonym.

    Mixing POST and URL Parameters

       $color = $query->url_param('color');
    
    It is possible for a script to receive CGI parameters in the URL as well as in the fill-out form by creating a form that POSTs to a URL containing a query string (a "?" mark followed by arguments). The param() method will always return the contents of the POSTed fill-out form, ignoring the URL's query string. To retrieve URL parameters, call the url_param() method. Use it in the same way as param(). The main difference is that it allows you to read the parameters, but not set them.

    Under no circumstances will the contents of the URL query string interfere with similarly-named CGI parameters in POSTed forms. If you try to mix a URL query string with a form submitted with the GET method, the results will not be what you expect.

    Table of contents


    Calling CGI Functions that Take Multiple Arguments

    In versions of CGI.pm prior to 2.0, it could get difficult to remember the proper order of arguments in CGI function calls that accepted five or six different arguments. As of 2.0, there's a better way to pass arguments to the various CGI functions. In this style, you pass a series of name=>argument pairs, like this:
       $field = $query->radio_group(-name=>'OS',
                                    -values=>[Unix,Windows,Macintosh],
                                    -default=>'Unix');
    
    The advantages of this style are that you don't have to remember the exact order of the arguments, and if you leave out a parameter, it will usually default to some reasonable value. If you provide a parameter that the method doesn't recognize, it will usually do something useful with it, such as incorporating it into the HTML tag as an attribute. For example if Netscape decides next week to add a new JUSTIFICATION parameter to the text field tags, you can start using the feature without waiting for a new version of CGI.pm:
       $field = $query->textfield(-name=>'State',
                                  -default=>'gaseous',
                                  -justification=>'RIGHT');
    
    This will result in an HTML tag that looks like this:
       <INPUT TYPE="textfield" NAME="State" VALUE="gaseous"
              JUSTIFICATION="RIGHT">
    
    Parameter names are case insensitive: you can use -name, or -Name or -NAME. You don't have to use the hyphen if you don't want to. After creating a CGI object, call the use_named_parameters() method with a nonzero value. This will tell CGI.pm that you intend to use named parameters exclusively:
       $query = new CGI;
       $query->use_named_parameters(1);
       $field = $query->radio_group('name'=>'OS',
                                    'values'=>['Unix','Windows','Macintosh'],
                                    'default'=>'Unix');
    
    Actually, CGI.pm only looks for a hyphen in the first parameter. So you can leave it off subsequent parameters if you like. Something to be wary of is the potential that a string constant like "values" will collide with a keyword (and in fact it does!) While Perl usually figures out when you're referring to a function and when you're referring to a string, you probably should put quotation marks around all string constants just to play it safe.

    HTML/HTTP parameters that contain internal hyphens, such as -Content-language can be passed by putting quotes around them, or by using an underscore for the second hyphen, e.g. -Content_language.

    The fact that you must use curly {} braces around the attributes passed to functions that create simple HTML tags but don't use them around the arguments passed to all other functions has many people, including myself, confused. As of 2.37b7, the syntax is extended to allow you to use curly braces for all function calls:

       $field = $query->radio_group({-name=>'OS',
                                    -values=>[Unix,Windows,Macintosh],
                                    -default=>'Unix'});
    
    Table of contents

    Creating the HTTP Header

    Creating the Standard Header for a Virtual Document

       print $query->header('image/gif');
    
    This prints out the required HTTP Content-type: header and the requisite blank line beneath it. If no parameter is specified, it will default to 'text/html'.

    An extended form of this method allows you to specify a status code and a message to pass back to the browser:

       print $query->header(-type=>'image/gif',
                            -status=>'204 No Response');
    
    This presents the browser with a status code of 204 (No response). Properly-behaved browsers will take no action, simply remaining on the current page. (This is appropriate for a script that does some processing but doesn't need to display any results, or for a script called when a user clicks on an empty part of a clickable image map.)

    Several other named parameters are recognized. Here's a contrived example that uses them all:

       print $query->header(-type=>'image/gif',
                            -status=>'402 Payment Required',
                            -expires=>'+3d',
                            -cookie=>$my_cookie,
                            -Cost=>'$0.02');
    

    -expires

    Some browsers, such as Internet Explorer, cache the output of CGI scripts. Others, such as Netscape Navigator do not. This leads to annoying and inconsistent behavior when going from one browser to another. You can force the behavior to be consistent by using the -expires parameter. When you specify an absolute or relative expiration interval with this parameter, browsers and proxy servers will cache the script's output until the indicated expiration date. The following forms are all valid for the -expires field:
    	+30s                              30 seconds from now
    	+10m                              ten minutes from now
    	+1h	                          one hour from now
            -1d                               yesterday (i.e. "ASAP!")
    	now                               immediately
    	+3M                               in three months
            +10y                              in ten years time
    	Thu, 25-Apr-1999 00:40:33 GMT     at the indicated time & date
    
    When you use -expires, the script also generates a correct time stamp for the generated document to ensure that your clock and the browser's clock agree. This allows you to create documents that are reliably cached for short periods of time.

    CGI::expires() is the static function call used internally that turns relative time intervals into HTTP dates. You can call it directly if you wish.

    -cookie

    The -cookie parameter generates a header that tells Netscape browsers to return a "magic cookie" during all subsequent transactions with your script. HTTP cookies have a special format that includes interesting attributes such as expiration time. Use the cookie() method to create and retrieve session cookies. The value of this parameter can be either a scalar value or an array reference. You can use the latter to generate multiple cookies. (You can use the alias -cookies for readability.)

    -nph

    The -nph parameter, if set to a non-zero value, will generate a valid header for use in no-parsed-header scripts. For example:
    print $query->header(-nph=>1,
                            -status=>'200 OK',
                            -type=>'text/html');
    
    You will need to use this if:
    1. You are using Microsoft Internet Information Server.
    2. If you need to create unbuffered output, for example for use in a "server push" script.
    3. To take advantage of HTTP extensions not supported by your server.
    See Using NPH Scripts for more information.

    Other header fields

    Any other parameters that you pass to header() will be turned into correctly formatted HTTP header fields, even if they aren't called for in the current HTTP spec. For example, the example that appears a few paragraphs above creates a field that looks like this:
       Cost: $0.02
    
    You can use this to take advantage of new HTTP header fields without waiting for the next release of CGI.pm.

    Creating the Header for a Redirection Request

       print $query->redirect('http://somewhere.else/in/the/world');
    
    This generates a redirection request for the remote browser. It will immediately go to the indicated URL. You should exit soon after this. Nothing else will be displayed.

    You can add your own headers to this as in the header() method.

    You should always use absolute or full URLs in redirection requests. Relative URLs will not work correctly.

    An alternative syntax for redirect() is:

    print $query->redirect(-location=>'http://somewhere.else/',
                              -nph=>1);
    
    The -location parameter gives the destination URL. You may also use -uri or -url if you prefer.

    The -nph parameter, if non-zero tells CGI.pm that this script is running as a no-parsed-header script. See Using NPH Scripts for more information.

    The -method parameter tells the browser what method to use for redirection. This is handy if, for example, your script was called from a fill-out form POST operation, but you want to redirect the browser to a static page that requires a GET.

    All other parameters recognized by the header() method are also valid in redirect. Table of contents


    HTML Shortcuts

    Creating an HTML Header

       named parameter style
       print $query->start_html(-title=>'Secrets of the Pyramids',
                                -author=>'fred@capricorn.org',
                                -base=>'true',
    			    -meta=>{'keywords'=>'pharoah secret mummy',
                                        'copyright'=>'copyright 1996 King Tut'},
    			    -style=>{'src'=>'/styles/style1.css'},
                                -dtd=>1,
                                -BGCOLOR=>'blue');
    
       old style
       print $query->start_html('Secrets of the Pyramids',
                                'fred@capricorn.org','true');
    
    This will return a canned HTML header and the opening <BODY> tag. All parameters are optional:

    Ending an HTML Document

      print $query->end_html
    
    This ends an HTML document by printing the </BODY> </HTML> tags.

    Other HTML Tags

    CGI.pm provides shortcut methods for many other HTML tags. All HTML2 tags and the Netscape extensions are supported, as well as the HTML3 tags that are in common usage (including tables). Unpaired tags, paired tags, and tags that contain attributes are all supported using a simple syntax.

    To see the list of HTML tags that are supported, open up the CGI.pm file and look at the functions defined in the %EXPORT_TAGS array.

    Unpaired Tags

    Unpaired tags include <P>, <HR> and <BR>. The syntax for creating them is:
       print $query->hr;
    
    This prints out the text "<hr>".

    Paired Tags

    Paired tags include <EM>, <I> and the like. The syntax for creating them is:
       print $query->em("What a silly art exhibit!");
    
    This prints out the text "<em>What a silly art exhibit!</em>".

    You can pass as many text arguments as you like: they'll be concatenated together with spaces. This allows you to create nested tags easily:

       print $query->h3("The",$query->em("silly"),"art exhibit");
    
    This creates the text:
       <h3>The <em>silly</em> art exhibit</h3>
    

    When used in conjunction with the import facility, the HTML shortcuts can make CGI scripts easier to read. For example:

       use CGI qw/:standard/;
       print h1("Road Guide"),
             ol(
              li(a({href=>"start.html"},"The beginning")),
              li(a({href=>"middle.html"},"The middle")),
              li(a({href=>"end.html"},"The end"))
             );
    

    Most HTML tags are represented as lowercase function calls. There are a few exceptions:

    1. The <tr> tag used to start a new table row conflicts with the perl translate function tr(). Use TR() or Tr() instead.
    2. The <param> tag used to pass parameters to an applet conflicts with CGI's own param() method. Use PARAM() instead.
    3. The <select> tag used to create selection lists conflicts with Perl's select() function. Use Select() instead.
    4. The <sub> tag used to create subscripts conflicts wit Perl's operator for creating subroutines. Use Sub() instead.

    Tags with Attributes

    To add attributes to an HTML tag, simply pass a reference to an associative array as the first argument. The keys and values of the associative array become the names and values of the attributes. For example, here's how to generate an <A> anchor link:
       use CGI qw/:standard/;
       print a({-href=>"bad_art.html"},"Jump to the silly exhibit");
    
       <A HREF="bad_art.html">Jump to the silly exhibit</A>
    
    You may dispense with the dashes in front of the attribute names if you prefer:
       print img {src=>'fred.gif',align=>'LEFT'};
    
       <IMG ALIGN="LEFT" SRC="fred.gif">
    
    Sometimes an HTML tag attribute has no argument. For example, ordered lists can be marked as COMPACT, or you wish to specify that a table has a border with <TABLE BORDER>. The syntax for this is an argument that that points to an undef string:
       print ol({compact=>undef},li('one'),li('two'),li('three'));
    
    Prior to CGI.pm version 2.41, providing an empty ('') string as an attribute argument was the same as providing undef. However, this has changed in order to accomodate those who want to create tags of the form <IMG ALT="">. The difference is shown in this table:
    CODE RESULT
    img({alt=>undef}) <IMG ALT>
    img({alt=>''}) <IMT ALT="">

    Distributive HTML Tags and Tables

    All HTML tags are distributive. If you give them an argument consisting of a reference to a list, the tag will be distributed across each element of the list. For example, here's one way to make an ordered list:
    print ul(
            li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy']);
          );
    
    This example will result in HTML output that looks like this:
    <UL>
      <LI TYPE="disc">Sneezy</LI>
      <LI TYPE="disc">Doc</LI>
      <LI TYPE="disc">Sleepy</LI>
      <LI TYPE="disc">Happy</LI>
    </UL>
    
    You can take advantage of this to create HTML tables easily and naturally. Here is some code and the HTML it outputs:
    use CGI qw/:standard :html3 -no_debug/;
    print table({-border=>undef},
            caption(strong('When Should You Eat Your Vegetables?')),
            Tr({-align=>CENTER,-valign=>TOP},
            [
               th(['','Breakfast','Lunch','Dinner']),
               th('Tomatoes').td(['no','yes','yes']),
               th('Broccoli').td(['no','no','yes']),
               th('Onions').td(['yes','yes','yes'])
            ]
          )
    );
    
    When Should You Eat Your Vegetables?
    Breakfast Lunch Dinner
    Tomatoesno yes yes
    Broccolino no yes
    Onionsyes yes yes

    Notice the use of -no_debug in a program that we intend to call from the command line.

    If you want to produce tables programatically, you can do it this way:

    use CGI qw/:standard :html3 -no_debug/;
    @values = (1..5);
    
    @headings = ('N','N'.sup('2'),'N'.sup('3'));
    @rows = th(\@headings);
    foreach $n (@values) {
       push(@rows,td([$n,$n**2,$n**3]));
    }
    print table({-border=>undef,-width=>'25%'},
                caption(b('Wow.  I can multiply!')),
                Tr(\@rows)
               );
    
    Wow. I can multiply!
    N N2 N3
    1 1 1
    2 4 8
    3 9 27
    4 16 64
    5 25 125
    Table of contents

    Creating Forms

    General note 1. The various form-creating methods all return strings to the caller. These strings will contain the HTML code that will create the requested form element. You are responsible for actually printing out these strings. It's set up this way so that you can place formatting tags around the form elements.

    General note 2. The default values that you specify for the forms are only used the first time the script is invoked. If there are already values present in the query string, they are used, even if blank.

    If you want to change the value of a field from its previous value, you have two choices:

    1. call the param() method to set it.
    2. use the -override (alias -force) parameter. (This is a new feature in 2.15) This forces the default value to be used, regardless of the previous value of the field:
             print $query->textfield(-name=>'favorite_color',
                                     -default=>'red',
      			       -override=>1);
             
    If you want to reset all fields to their defaults, you can:
    1. Create a special defaults button using the defaults() method.
    2. Create a hypertext link that calls your script without any parameters.
    General note 3. You can put multiple forms on the same page if you wish. However, be warned that it isn't always easy to preserve state information for more than one form at a time. See advanced techniques for some hints.

    General note 4. By popular demand, the text and labels that you provide for form elements are escaped according to HTML rules. This means that you can safely use "<CLICK ME>" as the label for a button. However, this behavior may interfere with your ability to incorporate special HTML character sequences, such as &Aacute; (Á) into your fields. If you wish to turn off automatic escaping, call the autoEscape() method with a false value immediately after creating the CGI object:

         $query = new CGI;
         $query->autoEscape(undef);
    
    You can turn autoescaping back on at any time with $query->autoEscape('yes')

    Form Elements

  • Opening a form
  • Text entry fields
  • Big text entry fields
  • Password fields
  • File upload fields
  • Popup menus
  • Scrolling lists
  • Checkbox groups
  • Individual checkboxes
  • Radio button groups
  • Submission buttons
  • Reset buttons
  • Reset to defaults button
  • Hidden fields
  • Clickable Images
  • JavaScript Buttons
  • Autoescaping HTML
  • Up to table of contents

    Creating An Isindex Tag

       print $query->isindex($action);
    
    isindex() without any arguments returns an <ISINDEX> tag that designates your script as the URL to call. If you want the browser to call a different URL to handle the search, pass isindex() the URL you want to be called.

    Starting And Ending A Form

       print $query->startform($method,$action,$encoding);
         ...various form stuff...
       print $query->endform;
    
    startform() will return a <FORM> tag with the optional method, action and form encoding that you specify. endform() returns a </FORM> tag.

    The form encoding supports the "file upload" feature of Netscape 2.0 (and higher) and Internet Explorer 4.0 (and higher). The form encoding tells the browser how to package up the contents of the form in order to transmit it across the Internet. There are two types of encoding that you can specify:

    application/x-www-form-urlencoded
    This is the type of encoding used by all browsers prior to Netscape 2.0. It is compatible with many CGI scripts and is suitable for short fields containing text data. For your convenience, CGI.pm stores the name of this encoding type in $CGI::URL_ENCODED.
    multipart/form-data
    This is the newer type of encoding introduced by Netscape 2.0. It is suitable for forms that contain very large fields or that are intended for transferring binary data. Most importantly, it enables the "file upload" feature of Netscape 2.0 forms. For your convenience, CGI.pm stores the name of this encoding type in CGI::MULTIPART()

    Forms that use this type of encoding are not easily interpreted by CGI scripts unless they use CGI.pm or another library that knows how to handle them. Unless you are using the file upload feature, there's no particular reason to use this type of encoding.

    For compatability, the startform() method uses the older form of encoding by default. If you want to use the newer form of encoding By default, you can call start_multipart_form() instead of startform().

    If you plan to make use of the JavaScript features, you can provide startform() with the optional -name and/or -onSubmit parameters. -name has no effect on the display of the form, but can be used to give the form an identifier so that it can be manipulated by JavaScript functions. Provide the -onSubmit parameter in order to register some JavaScript code to be performed just before the form is submitted. This is useful for checking the validity of a form before submitting it. Your JavaScript code should return a value of "true" to let Netscape know that it can go ahead and submit the form, and "false" to abort the submission.

    Starting a Form that Uses the "File Upload" Feature

       print $query->start_multipart_form($method,$action,$encoding);
         ...various form stuff...
       print $query->endform;
    
    This has exactly the same usage as startform(), but it specifies form encoding type multipart/form-data as the default.

    Creating A Text Field

      Named parameter style
      print $query->textfield(-name=>'field_name',
    	                    -default=>'starting value',
    	                    -size=>50,
    	                    -maxlength=>80);
    
       Old style
      print $query->textfield('foo','starting value',50,80);
    
    textfield() will return a text input field. As with all these methods, the field will be initialized with its previous contents from earlier invocations of the script. If you want to force in the new value, overriding the existing one, see General note 2.

    When the form is processed, the value of the text field can be retrieved with:

          $value = $query->param('foo');
    

    JavaScripting: You can also provide -onChange, -onFocus, -onBlur, -onMouseOver, -onMouseOut and -onSelect parameters to register JavaScript event handlers.

    Creating A Big Text Field

       Named parameter style
       print $query->textarea(-name=>'foo',
    	 		  -default=>'starting value',
    	                  -rows=>10,
    	                  -columns=>50);
    
       Old style
       print $query->textarea('foo','starting value',10,50);
    
    textarea() is just like textfield(), but it allows you to specify rows and columns for a multiline text entry box. You can provide a starting value for the field, which can be long and contain multiple lines.

    JavaScripting: Like textfield(), you can provide -onChange, -onFocus, -onBlur, -onMouseOver, -onMouseOut and -onSelect parameters to register JavaScript event handlers.

    Creating A Password Field

       Named parameter style
       print $query->password_field(-name=>'secret',
    				-value=>'starting value',
    				-size=>50,
    				-maxlength=>80);
    
       Old style
       print $query->password_field('secret','starting value',50,80);
    
    password_field() is identical to textfield(), except that its contents will be starred out on the web page.

    Creating a File Upload Field

        Named parameters style
        print $query->filefield(-name=>'uploaded_file',
    	                    -default=>'starting value',
    	                    -size=>50,
    	 		    -maxlength=>80);
    
        Old style
        print $query->filefield('uploaded_file','starting value',50,80);
    
    filefield() will return a form field that prompts the user to upload a file. filefield() will return a file upload field for use with recent browsers. The browser will prompt the remote user to select a file to transmit over the Internet to the server. Other browsers currently ignore this field.

    In order to take full advantage of the file upload facility you must use the new multipart form encoding scheme. You can do this either by calling startform() and specify an encoding type of $CGI::MULTIPART or by using the new start_multipart_form() method. If you don't use multipart encoding, then you'll be able to retreive the name of the file selected by the remote user, but you won't be able to access its contents.

    When the form is processed, you can retrieve the entered filename by calling param().

           $filename = $query->param('uploaded_file');
    
    where "uploaded_file" is whatever you named the file upload field. Depending on the browser version, the filename that gets returned may be the full local file path on the remote user's machine, or just the bare filename. If a path is provided, the follows the path conventions of the local machine.

    The filename returned is also a file handle. You can read the contents of the file using standard Perl file reading calls:

    	# Read a text file and print it out
    	while (<$filename>) {
    	   print;
            }
    
            # Copy a binary file to somewhere safe
            open (OUTFILE,">>/usr/local/web/users/feedback");
    	while ($bytesread=read($filename,$buffer,1024)) {
    	   print OUTFILE $buffer;
            }
           close $filename;
    

    There are problems with the dual nature of the upload fields. If you use strict, then Perl will complain when you try to use a string as a filehandle. You can get around this by placing the file reading code in a block containing the no strict pragma. More seriously, it is possible for the remote user to type garbage into the upload field, in which case what you get from param() is not a filehandle at all, but a string.

    To be safe, use the upload() function (new in version 2.47). When called with the name of an upload field, upload() returns a filehandle, or undef if the parameter is not a valid filehandle.

         $fh = $query->upload('uploaded_file');
         while (<$fh>) {
    	   print;
         }
    

    This is the recommended idiom.

    You can have several file upload fields in the same form, and even give them the same name if you like (in the latter case param() will return a list of file names). However, if the user attempts to upload several files with exactly the same name, CGI.pm will only return the last of them. This is a known bug.

    When processing an uploaded file, CGI.pm creates a temporary file on your hard disk and passes you a file handle to that file. After you are finished with the file handle, CGI.pm unlinks (deletes) the temporary file. If you need to you can access the temporary file directly. Its name is stored inside the CGI object's "private" data, and you can access it by passing the file name to the tmpFileName() method:

           $filename = $query->param('uploaded_file');
           $tmpfilename = $query->tmpFileName($filename);
    

    The temporary file will be deleted automatically when your program exits unless you manually rename it. On some operating systems (such as Windows NT), you will need to close the temporary file's filehandle before your program exits. Otherwise the attempt to delete the temporary file will fail.

    A potential problem with the temporary file upload feature is that the temporary file is accessible to any local user on the system. In previous versions of this module, the temporary file was world readable, meaning that anyone could peak at what was being uploaded. As of version 2.36, the modes on the temp file have been changed to read/write by owner only. Only the Web server and its CGI scripts can access the temp file. Unfortunately this means that one CGI script can spy on another! To make the temporary files really private, set the CGI global variable $CGI::PRIVATE_TEMPFILES to 1. Alternatively, call the built-in function CGI::private_tempfiles(1), or just use CGI qw/-private_tempfiles. The temp file will now be unlinked as soon as it is created, making it inaccessible to other users. The downside of this is that you will be unable to access this temporary file directly (tmpFileName() will continue to return a string, but you will find no file at that location.) Further, since PRIVATE_TEMPFILES is a global variable, its setting will affect all instances of CGI.pm if you are running mod_perl. You can work around this limitation by declaring $CGI::PRIVATE_TEMPFILES as a local at the top of your script.

    On Windows NT, it is impossible to make a temporary file private. This is because Windows doesn't allow you to delete a file before closing it.

    Usually the browser sends along some header information along with the text of the file itself. Currently the headers contain only the original file name and the MIME content type (if known). Future browsers might send other information as well (such as modification date and size). To retrieve this information, call uploadInfo(). It returns a reference to an associative array containing all the document headers. For example, this code fragment retrieves the MIME type of the uploaded file (be careful to use the proper capitalization for "Content-Type"!):

           $filename = $query->param('uploaded_file');
           $type = $query->uploadInfo($filename)->{'Content-Type'};
           unless ($type eq 'text/html') {
    	  die "HTML FILES ONLY!";
           }
    

    JavaScripting: Like textfield(), filefield() accepts -onChange, -onFocus, -onBlur, -onMouseOver, -onMouseOut and -onSelect parameters to register JavaScript event handlers. Caveats and potential problems in the file upload feature.

    Creating A Popup Menu

      Named parameter style
      print $query->popup_menu(-name=>'menu_name',
                                -values=>[qw/eenie meenie minie/], 
    			    -labels=>{'eenie'=>'one',
                                             'meenie'=>'two',
                                             'minie'=>'three'},
    	                    -default=>'meenie');
    
      print $query->popup_menu(-name=>'menu_name',
    			    -values=>['eenie','meenie','minie'],
    	                    -default=>'meenie');
      
      Old style
      print $query->popup_menu('menu_name',
                                  ['eenie','meenie','minie'],'meenie',
                                  {'eenie'=>'one','meenie'=>'two','minie'=>'three'});
    
    popup_menu() creates a menu. When the form is processed, the selected value of the popup menu can be retrieved using:
         $popup_menu_value = $query->param('menu_name');
    
    JavaScripting: You can provide -onChange, -onFocus, -onMouseOver, -onMouseOut, and -onBlur parameters to register JavaScript event handlers.

    Creating A Scrolling List

       Named parameter style
       print $query->scrolling_list(-name=>'list_name',
                                    -values=>['eenie','meenie','minie','moe'],
                                    -default=>['eenie','moe'],
    	                        -size=>5,
    	                        -multiple=>'true',
                                    -labels=>\%labels);
    
       Old style
       print $query->scrolling_list('list_name',
                                    ['eenie','meenie','minie','moe'],
                                    ['eenie','moe'],5,'true',
                                    \%labels);
    
    
    scrolling_list() creates a scrolling list. When this form is processed, all selected list items will be returned as a list under the parameter name 'list_name'. The values of the selected items can be retrieved with:
         @selected = $query->param('list_name');
    
    JavaScripting: You can provide -onChange, -onFocus, -onMouseOver, -onMouseOut and -onBlur parameters to register JavaScript event handlers.

    Creating A Group Of Related Checkboxes

       Named parameter style
       print $query->checkbox_group(-name=>'group_name',
                                    -values=>['eenie','meenie','minie','moe'],
                                    -default=>['eenie','moe'],
    	                        -linebreak=>'true',
    	                        -labels=>\%labels);
    
       Old Style
       print $query->checkbox_group('group_name',
                                    ['eenie','meenie','minie','moe'],
                                    ['eenie','moe'],'true',\%labels);
    
       HTML3 Browsers Only
       print $query->checkbox_group(-name=>'group_name',
                                    -values=>['eenie','meenie','minie','moe'],
                                    -rows=>2,-columns=>2);
    
    checkbox_group() creates a list of checkboxes that are related by the same name. When the form is processed, the list of checked buttons in the group can be retrieved like this:
         @turned_on = $query->param('group_name');
    
    This function actually returns an array of button elements. You can capture the array and do interesting things with it, such as incorporating it into your own tables or lists. The -nolabels option is also useful in this regard:
           @h = $query->checkbox_group(-name=>'choice',
                                        -value=>['fee','fie','foe'],
                                        -nolabels=>1);
           create_nice_table(@h);
    
    JavaScripting: You can provide an -onClick parameter to register some JavaScript code to be performed every time the user clicks on any of the buttons in the group.

    Creating A Standalone Checkbox

       Named parameter list
       print $query->checkbox(-name=>'checkbox_name',
    			   -checked=>'checked',
    		           -value=>'TURNED ON',
    		           -label=>'Turn me on');
    
       Old style
       print $query->checkbox('checkbox_name',1,'TURNED ON','Turn me on');
    
    checkbox() is used to create an isolated checkbox that isn't logically related to any others. The value of the checkbox can be retrieved using:
         $turned_on = $query->param('checkbox_name');
    
    JavaScripting: You can provide an -onClick parameter to register some JavaScript code to be performed every time the user clicks on the button.

    Creating A Radio Button Group

       Named parameter style
       print $query->radio_group(-name=>'group_name',
    			     -values=>['eenie','meenie','minie'],
                                 -default=>'meenie',
    			     -linebreak=>'true',
    			     -labels=>\%labels);
    
       Old style
       print $query->radio_group('group_name',['eenie','meenie','minie'],
                                              'meenie','true',\%labels);
    
       HTML3-compatible browsers only
       print $query->radio_group(-name=>'group_name',
                                    -values=>['eenie','meenie','minie','moe'],
    	                        -rows=>2,-columns=>2);
    
    radio_group() creates a set of logically-related radio buttons. Turning one member of the group on turns the others off. When the form is processed, the selected radio button can be retrieved using:
           $which_radio_button = $query->param('group_name');
    
    This function actually returns an array of button elements. You can capture the array and do interesting things with it, such as incorporating it into your own tables or lists The -nolabels option is useful in this regard.:
           @h = $query->radio_group(-name=>'choice',
                                     -value=>['fee','fie','foe'],
                                     -nolabels=>1);
           create_nice_table(@h);
    

    JavaScripting: You can provide an -onClick parameter to register some JavaScript code to be performed every time the user clicks on any of the buttons in the group.

    Creating A Submit Button

       Named parameter style
       print $query->submit(-name=>'button_name',
    		        -value=>'value');
    
      Old style
      print $query->submit('button_name','value');
    
    submit() will create the query submission button. Every form should have one of these. JavaScripting: You can provide an -onClick parameter to register some JavaScript code to be performed every time the user clicks on the button. You can't prevent a form from being submitted, however. You must provide an -onSubmit handler to the form itself to do that.

    Creating A Reset Button

      print $query->reset
    
    reset() creates the "reset" button. It undoes whatever changes the user has recently made to the form, but does not necessarily reset the form all the way to the defaults. See defaults() for that. It takes the optional label for the button ("Reset" by default). JavaScripting: You can provide an -onClick parameter to register some JavaScript code to be performed every time the user clicks on the button.

    Creating A Defaults Button

      print $query->defaults('button_label')
    
    defaults() creates "reset to defaults" button. It takes the optional label for the button ("Defaults" by default). When the user presses this button, the form will automagically be cleared entirely and set to the defaults you specify in your script, just as it was the first time it was called.

    Creating A Hidden Field

       Named parameter style
       print $query->hidden(-name=>'hidden_name',
                            -default=>['value1','value2'...]);
    
       Old style
       print $query->hidden('hidden_name','value1','value2'...);
    
    hidden() produces a text field that can't be seen by the user. It is useful for passing state variable information from one invocation of the script to the next. [CAUTION] As of version 2.0 I have changed the behavior of hidden fields once again. Read this if you use hidden fields.

    Hidden fields used to behave differently from all other fields: the provided default values always overrode the "sticky" values. This was the behavior people seemed to expect, however it turns out to make it harder to write state-maintaining forms such as shopping cart programs. Therefore I have made the behavior consistent with other fields.

    Just like all the other form elements, the value of a hidden field is "sticky". If you want to replace a hidden field with some other values after the script has been called once you'll have to do it manually before writing out the form element:

         $query->param('hidden_name','new','values','here');
         print $query->hidden('hidden_name');
    
    Fetch the value of a hidden field this way:
        $hidden_value = $query->param('hidden_name');
                -or (for values created with arrays)-
        @hidden_values = $query->param('hidden_name');
    

    Creating a Clickable Image Button

       Named parameter style
       print $query->image_button(-name=>'button_name',
                                  -src=>'/images/NYNY.gif',
                                  -align=>'MIDDLE');	
    
       Old style
       print $query->image_button('button_name','/source/URL','MIDDLE');
    
    
    image_button() produces an inline image that acts as a submission button. When selected, the form is submitted and the clicked (x,y) coordinates are submitted as well. When the image is clicked, the results are passed to your script in two parameters named "button_name.x" and "button_name.y", where "button_name" is the name of the image button.
        $x = $query->param('button_name.x');
        $y = $query->param('button_name.y');
    
    JavaScripting: Current versions of JavaScript do not honor the -onClick handler, unlike other buttons.

    Creating a JavaScript Button

       Named parameter style
       print $query->button(-name=>'button1',
                               -value=>'Click Me',
                               -onClick=>'doButton(this)');	
    
       Old style
       print $query->image_button('button1','Click Me','doButton(this)');
    
    
    button() creates a JavaScript button. When the button is pressed, the JavaScript code pointed to by the -onClick parameter is executed. This only works with Netscape 2.0 and higher. Other browsers do not recognize JavaScript and probably won't even display the button. See JavaScripting for more information.

    Controlling HTML Autoescaping

    By default, if you use a special HTML character such as >, < or & as the label or value of a button, it will be escaped using the appropriate HTML escape sequence (e.g. &gt;). This lets you use anything at all for the text of a form field without worrying about breaking the HTML document. However, it may also interfere with your ability to use special characters, such as Á as default contents of fields. You can turn this feature on and off with the method autoEscape().

    Use

        $query->autoEscape(undef);
    
    to turn automatic HTML escaping off, and
        $query->autoEscape('true');
    
    to turn it back on.

    Importing CGI Methods

    A large number of scripts allocate only a single query object, use it to read parameters or to create a fill-out form, and then discard it. For this type of script, it may be handy to import CGI module methods into your name space. The most common syntax for this is:
    use CGI qw(:standard);
    
    This imports the standard methods into your namespace. Now instead of getting parameters like this:
    use CGI;
    $dinner = $query->param('entree');
    
    You can do it like this:
    use CGI qw(:standard);
    $dinner = param('entree');
    
    Similarly, instead of creating a form like this:
    print $query->start_form,
          "Check here if you're happy: ",
          $query->checkbox(-name=>'happy',-value=>'Y',-checked=>1),
          "<P>",
          $query->submit,
          $query->end_form;
    
    You can create it like this:
    print start_form,
          "Check here if you're happy: ",
          checkbox(-name=>'happy',-value=>'Y',-checked=>1),
          p,
          submit,
          end_form;
    
    Even though there's no CGI object in view in the second example, state is maintained using an implicit CGI object that's created automatically. The form elements created this way are sticky, just as before. If you need to get at the implicit CGI object directly, you can refer to it as:
    $CGI::Q;
    

    The use CGI statement is used to import method names into the current name space. There is a slight overhead for each name you import, but ordinarily is nothing to worry about. You can import selected method names like this:

       use CGI qw(header start_html end_html);
    
    Ordinarily, however, you'll want to import groups of methods using export tags. Export tags refer to sets of logically related methods which are imported as a group with use. Tags are distinguished from ordinary methods by beginning with a ":" character. This example imports the methods dealing with the CGI protocol (param() and the like) as well as shortcuts that generate HTML2-compliant tags:
    use CGI qw(:cgi :html2);
    
    Currently there are 8 method families defined in CGI.pm. They are:
    :cgi
    These are all the tags that support one feature or another of the CGI protocol, including param(), path_info(), cookie(), request_method(), header() and the like.
    :form
    These are all the form element-generating methods, including start_form(), textfield(), etc.
    :html2
    These are HTML2-defined shortcuts such as br(), p() and head(). It also includes such things as start_html() and end_html() that aren't exactly HTML2, but are close enough.
    :html3
    These contain various HTML3 tags for tables, frames, super- and subscripts, applets and other objects.
    :netscape
    These are Netscape extensions not included in the HTML3 category including blink() and center().
    :html
    These are all the HTML generating shortcuts, comprising the union of html2, html3, and netscape.
    :multipart
    These are various functions that simplify creating documents of the various multipart MIME types, and are useful for implementing server push.
    :standard
    This is the union of html2, form, and :cgi (everything except the HTML3 and Netscape extensions).
    :all
    This imports all the public methods into your namespace!

    Pragmas

    In addition to importing individual methods and method families, use CGI recognizes several pragmas, all proceeded by dashes.
    -any
    When you use CGI -any, then any method that the query object doesn't recognize will be interpreted as a new HTML tag. This allows you to support the next ad hoc Netscape or Microsoft HTML extension. For example, to support Netscape's latest tag, <GRADIENT> (which causes the user's desktop to be flooded with a rotating gradient fill until his machine reboots), you can use something like this:
          use CGI qw(-any);
          $q=new CGI;
          print $q->gradient({speed=>'fast',start=>'red',end=>'blue'});
          
    Since using any causes any mistyped method name to be interpreted as an HTML tag, use it with care or not at all.

    -compile
    This causes the indicated autoloaded methods to be compiled up front, rather than deferred to later. This is useful for scripts that run for an extended period of time under FastCGI or mod_perl, and for those destined to be crunched by Malcom Beattie's Perl compiler. Use it in conjunction with the methods or method familes you plan to use.
          use CGI qw(-compile :standard :html3);
          
    or even
          use CGI qw(-compile :all);
          

    Note that using the -compile pragma in this way will always have the effect of importing the compiled functions into the current namespace. If you want to compile without importing use the compile() method instead.

    -autoload
    Overrides the autoloader so that any function in your program that is not recognized is referred to CGI.pm for possible evaluation. This allows you to use all the CGI.pm functions without adding them to your symbol table, which is of concern for mod_perl users who are worried about memory consumption. Warning: when -autoload is in effect, you cannot use "poetry mode" (functions without the parenthesis). Use hr() rather than hr, or add something like use subs qw/hr p header/ to the top of your script.

    -nph
    This makes CGI.pm produce a header appropriate for an NPH (no parsed header) script. You may need to do other things as well to tell the server that the script is NPH. See the discussion of NPH scripts below.

    -newstyle_urls
    Separate the name=value pairs in CGI parameter query strings with semicolons rather than ampersands. For example:
    ?name=fred;age=24;favorite_color=3
    
    Semicolon-delimited query strings are always accepted, but will not be emitted by self_url() and query_string() unless the -newstyle_urls pragma is specified.

    -no_debug
    This turns off the command-line processing features. If you want to run a CGI.pm script from the command line to produce HTML, and you don't want it pausing to request CGI parameters from standard input, then use this pragma:
          use CGI qw(-no_debug :standard);
          
    See debugging for more details.

    -private_tempfiles
    CGI.pm can process uploaded file. Ordinarily it spools the uploaded file to a temporary directory, then deletes the file when done. However, this opens the risk of eavesdropping as described in the file upload section. Another CGI script author could peek at this data during the upload, even if it is confidential information. On Unix systems, the -private_tempfiles pragma will cause the temporary file to be unlinked as soon as it is opened and before any data is written into it, eliminating the risk of eavesdropping.

    Special Forms for Importing HTML-Tag Functions

    Many of the methods generate HTML tags. As described below, tag functions automatically generate both the opening and closing tags. For example:
      print h1('Level 1 Header');
    
    produces
      <H1>Level 1 Header</H1>
    
    There will be some times when you want to produce the start and end tags yourself. In this case, you can use the form start_Itag_name and end_Itag_name, as in:
      print start_h1,'Level 1 Header',end_h1;
    
    With a few exceptions (described below), start_tag_name and end_Itag_name functions are not generated automatically when you use CGI. However, you can specify the tags you want to generate start/end functions for by putting an asterisk in front of their name, or, alternatively, requesting either "start_tag_name" or "end_tag_name" in the import list.

    Example:

      use CGI qw/:standard *table start_ul/;
    
    In this example, the following functions are generated in addition to the standard ones:
    1. start_table() (generates a <TABLE> tag)
    2. end_table() (generates a </TABLE> tag)
    3. start_ul() (generates a <UL> tag)
    4. end_ul() (generates a </UL> tag)

    PRETTY-PRINTING HTML

    By default, all the HTML produced by these functions comes out as one long line without carriage returns or indentation. This is yuck, but it does reduce the size of the documents by 10-20%. To get pretty-printed output, please use CGI::Pretty, a subclass contributed by Brian Paulsen.

    Optional Utility Functions

    In addition to the standard imported functions, there are a few optional functions that you must request by name if you want them. They were originally intended for internal use only, but are now made available by popular request.

    escape(), unescape()

    use CGI qw/escape unescape/;
    $q = escape('This $string contains ~wonderful~ characters');
    $u = unescape($q);
    
    These functions escape and unescape strings according to the URL hex escape rules. For example, the space character will be converted into the string "%20".

    escapeHTML(), unescapeHTML()

    use CGI qw/escapeHTML unescapeHTML/;
    $q = escapeHTML('This string is <illegal> html!');
    $u = unescapeHTML($q);
    
    These functions escape and unescape strings according to the HTML character entity rules. For example, the character < will be escaped as &lt;.

    compile()

    Ordinarily CGI.pm autoloads most of its functions on an as-needed basis. This speeds up the loading time by deferring the compilation phase. However, if you are using mod_perl, FastCGI or another system that uses a persistent Perl interpreter, you will want to precompile the methods at initialization time. To accomplish this, call the package function compile() like this:
    use CGI ();
    CGI->compile(':all');
    
    The arguments to compile() are a list of method names or sets, and are identical to those accepted by the use operator.

    Debugging

    If you are running the script from the command line or in the perl debugger, you can pass the script a list of keywords or parameter=value pairs on the command line or from standard input (you don't have to worry about tricking your script into reading from environment variables). You can pass keywords like this:
       my_script.pl keyword1 keyword2 keyword3
    
    or this:
       my_script.pl keyword1+keyword2+keyword3
    
    or this:
       my_script.pl name1=value1 name2=value2
    
    or this:
       my_script.pl name1=value1&name2=value2
    
    or even by sending newline-delimited parameters to standard input:
       % my_script.pl
       first_name=fred
       last_name=flintstone
       occupation='granite miner'
       ^D
    

    When debugging, you can use quotation marks and the backslash character to escape spaces and other funny characters in exactly the way you would in the shell (which is namontribpatiole() See Th o it is chcript M>orle stct -onClnow msubsequet() will cunctioe> M>orle stct hq = escap i time the user -onheckboxshod ffor that. It M>orldSTRONG> ct er, parameters named "bu . l cunmay be handy to import CGIgt;sub described in the

    label's used t-hq = es your"bt;tionbel   l cunmay be hand
    the HTML
    Old style
    codeu want params that tre>ne l M>or ioe>
      in thE>
      ortcuts sm is sen@lehman10".
    
    -srregisPRE>
    itextsns into for ct er's us. Thkquote>The thibel fyn b t (-align
    
    , an.T or 
    IDDLE     is field is (such.al.
    You cif yoYimage is cl    r, the resulise resu your script is  cn_nami in tin thIDDLEf thethe < buttion.
    < butt');
    ge_busionst()     p wantform ng>Jgistes.
    
    
    buttoA NAM3>CrttonsavaSc
    
    
    
    
      
      
    aramet ButML
    OG>-na;button. On e=>groupt" bu,
      t;but to efirst          -vare>
    lgt;'Click MMe',
    ontag_namegestrong>use CGI statem $querE  are thayen dee details.
          

    met_an fieeference to -values. rM3>start/end

    us scripts allocate only a st;hiddwI$ uring the
     hclharacte'ret to pue sequotyaracte're; as d 
    from standarte> lTML('Thisle to be unlinked as
    y also those acce(res 
  • ge_busi_ for runnierentecessu use CGI -anyeon. p will c of the ules.nli$mber of tns h of theimp>uelul wanyof theimponly a> my_scriptt/colhe loadiner');
  • produca

    w end_form;

    prodhadiner'); meand liue eyner'); mele met last_name=t
       use CGI qw(hea's noe you'llray r yags yeferenca  e the otton1',
     enticel fored',end=>'blue'});
        keywhe oues yeferyywhe 
    and end_I< pragmas, aplay.  It
          ny t $query-stI$iluments tomh shell tT re
    ouend end_yell tT ree>
    usehe 
     you  ts
    clng">Debugs you want to genera   quotecognize will be interprettlrul thayle: Ya ".pl
      ueognize yar>: Ya "form,
                  tarelirs on th" or
    "end_
    
    
     (gar uring mh shell  your st
    
    herse quoue uring y hermit, bt;tionbel lts alou can paounion of oce secng the -compile pragma in iner' bute. s chcruel ltsyr' bute. aintai> ortcuts smt mmed e="exam that is not recognthe <(e.g.1not to el ftulame.yut hputll thNG>lt a forPRE>

    no accomply. It l fto my_his iunctions without adding bt;tir-vits,HTML Oue

    no ytir-vits,u can resu your scritis l useI prust request by name ase CGI q $min tin thIDhnput:nd_hnerorted uets=>yt:nd_hner to se/PR hr, or add somesnts of fistI$lay.requestuhg con , areattrirduee HTMroyon , areaample t . want labeltpillgs you wample, the space char e<, usea as before.s Scr;para lawarniolabelthe impliTRONGng the ttI$$ctly,iffec efer torReset Bu> Similarelat

    use  to t0href="#n>blo e/;
    $q = e
    

    no my_script uote>

    >Namew'Click Me','dnye>start/$t (
    ML pa:al be used as tR  tagcte're; as lul wanyof the allocate onlyI.pm c
    met_an fie     defined s
  • gmsportedto yoby sendidwill l runnierea with a this :stser-visible LI>ge_busalaONG>tagcte're; aan ay. Itt: eo replar
  • o prs such as shoppinthis es it is /peneusing $yct er's us. Thkquote>use. Netsca $string uece(I y: <, usbre inftaiordiuse >use CGI te nameu use CGargumenct er'se=t

    ockquots.en defitI$$ct.valuemetersamtrong>-o interest, aplay.g uecof tn dPRmeu efermlray r s)'); xample impoec efaicrl'3 caon. <> ms us. Trulesiuse any t $quaduca

    In adpe()y M n In mmber "use oCa oCa froymte t sassii is u'); m>comp (n dr');un dee origissii i2 below. d importedsa rd importe -ne '.solor=3 . You can pass ke(scape p issywhe btng gnam nu r>hr ct a perd qw Rtandao Youotmte /aorppoMlems, s In adpe()debu the LEFTpBI-n unor. . <>dn. Res-o O I RRRform . .I I uu=oJfaauetendi nything yousener');t of Many of the methods generate HTML tags. As described below, tag functions automatically generate both the opening and closing tags. jSandard importue> /Thle hing sthecked=&gl vI n em*r> n6I em*eSTRONG>ognc r>/bloo imp eanq 'q 'q 'q Km*eSTRONGut tt;pianic >-o OelecttaoceedetattruW rW> Ta nary e nexteI < l L-Tag as starteyT t p BI-n unescapel-tcuts that SWb_ p BI-n uSJstahi_su usXeassii ifluatioL2-defed fi_erm . .I I These Thi/luatiw STR Icme it. FoI / sincu hre tht8,l to tiwognc r>/blode> (genemish thir create rse Yinte f -o O I RRRform . ./ca,-co, apnuy:nd_hn pac, $IHrriiI RThI <.ginally nexI D the risk of eaveThis allo.b/TEI the m syl name ao WbI als ectetrul thpIltheccot I Ne ing web'1bz Fu iman the ithpIlip ma s cutnts of fieldrapmf/IH>-iso b. sandy tromTioto tho oooag tohle Bhods ge bntpfnm I < r> eme=frrecteI resu Tnam sp ms us . e> r>hr Ir runnierentec usehe < on. w u twrI t;['varuery->io thec sT len name1p1These funct iito iHth(wsb3> Ir ifuncte> len name1p1Thes4lnput: t:scapes welIe some times wsta for u twrImnl 'lh]]]p". .the nrppoMle3t t:s y pl namet sasbdt:s y te< rL"ES=wI DI,>zg:zg: functuMEe now maIe> ms wstatct hq = esc e the ott eSTretchbThe sor.

    for u twrIa sel .DP0g y furt_or th* uitt eSkquote> name.9" R I len name1png tagsaR ueognlode> sorFsicaigie have oneorldSTRONG> ct er, parae oPuttt.t tThiluegti.the nrppoMle3t t:s y pl namet sasbdt:s y oPuto tiw lass cogdiner');rI @le : dropsBe < tohle R : dr pcontacomp tor examp Bhods gused as tR scrihU th;ns tewortgin peindeCLooDnics-use TRO q I RRRfotgddbmp Ble :u ilBco;['> tewortgt mnat or ionW (n, $I_Tre/pr <,i0> mestteI temS sucme f < l oPupima functiolul wao' rd qminer' m nunctcles. For g: /o metfIlikOr th* uitId >JavaSgs. e r)hWoinde functioons of in peindes u'); mctcleeaR I pcontachbThe pcontachbThe oPuccawarniolaI evlect.he Tauccawarndir>uu=ot.at you nteEao l cL..9" R IeI us scerd qweDI , an.T or IDDLE is indeCLoohodsLtTdefi iLoohodsLI ! l o;['> iL(tacomp tor examp Bho'1}o I or ionW (nJa apla neng from eI-n uneartD tnof your stn ton cre!ng yseous multnctioe>e Bhocomp torur s}nlt a nexLa apI e for u twrIa sel .Den .Den yywhe tD (gar unothing t a perd qwnturn aeyword1 keywortortlrugortlrugobemTI kicrlt_ul/;nIa areT(PqweDIanor ionW (nkicrlt_ul/;nIa n iotns uu=ot.at you nteEao l cL..9"JfaaueIe somecng tagsaR ue$y); <>Ja apla neng uu1er');|cG> /Thle hiIu e t. Fo/citeI en d z poec e is yiI mp for ct a ",w

    e Bhocomp torur s}nimpgSsasbdt:s backslyword1 keywortortlrugortlrugobemTI oPuccaOIs starpth* uitIde ng tagiIHry. iEMe at for u twrIa sel .Dn for td>TheOIs starpth* uidw qels=&IuT>, an.T or IDDLE is o ed as tR warndir>uOIs starpth* uitIdn for ic TheOIs starrd1 kI " er, I tsca . R\h mBco; to iit is >JavaSgs> oal

    ,aractoon. <> I Th(o uu1er'); len qu uu1er'); np perd .rh"ihretrtlcBlwa paramWT. .I I e Th(o zompO kquilmaE> No kqui/ xt( mi lts aloe>e ng tahg m.-O)I,I>z/Nay I I cttunoahkmarac4td>Thxt Youotmte /aorppoMl'xc o'I> oalofter ,t ofrmntpfnm | < uPM>osnyes,NimporI,I>z/Nay ct dirCx
    enerauetend z FE> No plcng tht dirCx
    enerauete)or tg<,ooa>T 2te nctioe>ionW "T'rppses alo Thi pl/citee>notou
    /o  )I  :mu  
    
    oI iause Ce,sehe <  Anbmp  Bho'1 
    
    oal snO
    lati a  Trs u 1plesct die >Nas u 1plesoeof theIFd>Trs u 1plescfe,-"o 2te HA>Ryou can usa
    
       usemecfpcial FoyI f useme  < l
     -> 
    hortI  e Bho
    rCx
    iopaBm sys st bDlicrlntt  
    L-*eSTRONGut=hIs R  <  t_tab noe derr#n r  T 2te autoNv: Ya uto tiw
    B  &lnd(cused as tR
    scrihU thng:T 2c R
    scriT 2etend    .in -)h9EnW (n
    us scedslue'}tlrugs pernI>z/Nay I
    R liug tnhcharal  mi  rtortlruggene R_ogs pebi=OGIgt;t;s gs :al be 
    ( $quet  iottchbTatt
    msCL )s1plefed f_hI  I  - >La 
    IDD ey
    >JavaSgs>"g tohi
    he liun < l  -o OelpetI  
    us scedslue'ac4td
    ed methodeh
      n <-*eSTRONGut=hIsion
    nter  m(I  ee
    
    uto titacom   mi  lts auI
    ir tga>T 2ease nct  pick qwnturn aeyword1 keyworf_hIi.ueTdefi.uetUd
    ust.e
       u3M  Thiimport Chb>tac
    
    oal  mi  awarndir>uOIs starpth* uilhT CL ))d1  reI  -o  nhchaDfbxc s,tics-on>useal bDn Ll .Dn "Zdns
    rniolnc f 
    z$Wf gt; 
    hort oh  Micr n c st   i;> 
    len tics-o',end
    
    Ao  a  nle,sced;Sm3(HaspeexIT CL ))
    ho
    I -ery-stI$blodho
    I -ery-stI$blodho
    I -erIt:
    ee
    
     
    ld>uot.iner'oan e hand -o  <   mi edrl uLE tghor jec Gblockquoteac c"Q  <.si e utPdD 
    ust.e
    hee.y' FH nou',shR
    q
    g:-o  
    latI  e Bh[oM fuyoI hIi.LHiou',shR
    'rppsel  pragma ieI enmadp;'ble are Hyhn r-
    3  ct.hn r-
    3 a a  nyeiopaBOI  dn.    nloAr't -o  ade  u'gp4> nhcnce again.  Resesu e t.
    FrIhs)tyou to sue CLoooag toYa osny',bpiw, t  -strings are  i>oa."tkqx ms fop3lou esw
    
    o(I/gGNnr_tonaotmf'pt thbs ailoIir>ud  s>.'ese aht,d ')=rt e Bgt; 
    eDI  nGte ieathe x;'blenC> tcy nhchad>n  In  IR
    euporToTSrm   mmbungln.voM fmke e ringdeew	yon
    ntek)A  <"ROmage  bbct    hq = esc "ai  tt  Ree I c /to .I c starpth* uot.it_i3M  ois"=OGIga;'blene I cngan  uu toa< ei 
    L-* 2ets>-o  <  d  
    
    Ta nou 
    ntR:
    m3(HaspeexIT xnou 
    ntRaphfe fun dnei 
    L-* 2ms,
     s. e>  e ng tahg toa< ei 
    tscapeuu=
    

    dng mh.g(R eupornuot. HTM0aahh_ Ta noan.T M frnTs R IaoceedetattruI lc:y te>ee I. Ia _'ngo t fe Bhoco. tol(rw perd qwe Bhoco. ailoIir> of te> oo be unl oPuc((tacomtfC!CIiloIiyC!CIi< )> toabL(),mikLw < l Ta no> torselflu_Be the ott.feeu nctAdeew yonsruW rsl R t8 4 5In1n i$ -vnC tor otton1nsor. l R t8defi.uete' perd ONG hk tha' alopI PiuIhn usa q=GPP9s)') ent name ao d m.lue'ac4attunAAd m.lue'h=Ja apI te> .sh .kh4 5I < It eteI ct dirCx cause.pihgfIlite> mge v" tcy R ytoacI ueJava.sx ueJbe ht o;l==WS_tlhqu . e> i aertannattsfrfu eI oe xtAcT aT e BhocoIt l id ONG st cally! tcy-& o(I/gousXeassii iflua Hk/gousXeassIDDLEaP2.'ese aht,d 'm_'ngo t fyn t fcall .sh/to, ts you totb4 5RJbDniI i he n, Rtandao are HyhnYsI_buttos]u totb4 feampog/cot$WI pport>e Bhoc 2. Fo/cite1 urin2onsyI < somecd,hxI d ttag.lIam torselflu_fyoo h/cot$WI pport>e BhOag.lIam<_w perto tcy R ytoacI ue sor.
    sdee ori ly,toacI ue ngan -o gR I te" but arCx
    are HyhnYsI_buttos]u totbetsc>by dtarrd1 kI qb/peindelyn{oII 4s genera4 feampog/cot$IcS

    ,aractoon. < gg2.'uNNy'ngoI>eI aE yon em nuu pgnd roymte t sauW rWhgfIlny ocoto titacotN4>(nn d m.lue'h=Ja apI te> are Rish thir creap$uI ut to -o O I arptmportii tmpv R t8 4 5I are Rit x
    are RinI 44 sho oou apI et th 5I tnoE RinIS Ige e In talecIam< uitIdyC!CIe nc /to< mI 4s g<1p__hleiu(rwkquoPmcaqb/Thle se _

    us sctartao use nW (n are Riga noDGao0 In ai thlodI HkquoPmcaqb/Thle senteksI Bi tn B-* 2mstrldv mi edrl e thI e>e thaSThi_aed e thRup ma"_dfaauetendi nymer t,I cForldSTRONG> ct er, parae oPuttt.t tThiluegti.the nrppoMle3t t:s y pl namet sasbdt:s y e BhOag.H 3eI i_aenC> tcy R NGleI are R cally! n:,s ae turer ! e thRup maortalUe>e thRupx


    are Rit l r>fmcstrldv h_e u e feP are Rit l tcye acoy dtarrd1pfnieJaicsoal ggc starp , > eI B-* 2mst qD/EEmpl eae> keyoopgSsasihs=&IuT>, alue'}nxI I uetenaR ,r3NN\L>)z u=,I; aolWsdineI Netfl J/IFHg ingdnW e aIe f_hIeapel-tcuo gclwanaurns 4 >R eupo .sh Ga WbI at wA enn perd s0 cIam eme=frreEme f WbI at wA for u twrIa s.requeaphls:

    for u twrIa s.requeaphls:

    IThe use lcIam< ui"NtId< for u fpit l .ort Netth* uotl mi edrl mi edrl -defed fYs=brl -de orCLoimqL.Pvarue o for yons=gTheOIs st bDnics< Ga f ere- uslgobemTD i 5I i_aqelharI ScraR gselo.b/Tzg: emeo=o/citn2>cIamgGNn I < l ->pianic tTnmie " oneu cedsl I d onGte l {oI g tags toa mia Igteywortou mNrshWaccePtetsctartao uSJstahn I <. WbIyI. e> cFug,/N-,,tol onO) nW (n IgeanGte dcorp4 havh* u Igea n te" but arCx


    are HyhnYsI_buttos]u totbetsd1E nfg> mi e Boe 2";e cot.hent h perpmTD iiobetsd1E nf $x-&ge5I i_aqe bO g tshWacekrate HArue oIF f). Youhyell nuc">uu= A> cFuF ingdo patMb;e cot.h> of te -)hmis st bD alordd(c te"le :u ilincO< teb/Thle imaP,afaaumes wstawtAse alord"snucme=wqbcitns ,reDnhtaeSTR FoeJavart tTnIVcIimp> y ts you totb4 5RJbSM>oPuResSe IFd z Fo/n EChL-*1(dmgobemTD .e 5I tnof y-de tnof y-dt ortn n tTcotty tpamheh*tr l zWI pport>dotcoPaqb/TccGcW atkquoeu ced=m ienI <>used as ginter iman tdh1png t1 c]EMi gR ,hnYsrnTa&zt2 _b/nd he BhoduiwwtAseagiacoy dtarrd1p tor1i_aqel,mort thastait!dttr as gint ri,IngduLE tg supLomTi,s ae turnsmnLnedsl2etend I 'm3(Hoht o;lt-halue1h.be tMfem> ncO< teS l zWI pporSir
    eTD tiehePuJa ihGleI<'i-sx (ai>qD/EEmpl <.;. erpgsbrl -dbemTD .o b. rppleape>saringdo path g> mi edrl -diaaeuC daiuis 8 4 _a g.tkquo1 taforCLoo)He neWidnsnaminter mng t1 *A(" :u ilingtgcstart1tafor sce ihg au pgnng oTnIIdmnt.in;,wntPioohohpheaedI nurugR .,"Whuatioowb/Thle /unr)s otbesfor Ppfsafor sce a)wefi.uetU s<m3(u T,EI id/unr)s otb5mi t>safoe.u D=ot esuYlt1 *AI ROed < acoy neattie'shWaccorICnIVcIi{oIi.Lue i jecud;t;s glt a nexLaelhqu eme1a nex,onhc(ipngoI b;elnEI id/unr)s oaminterIp.1notcma ioptcma ioptcma ioptcma ioptcma ioptcma ioptcma iopp3nractairs l thbTnaR Ihs)t rI < 'Mdaoegnng dg t1 *AbemTD eggc vnoI_o;dI SerCLooDn1 kI \h ,_o;dI m I es HrI _edple qI <.PRa ts,= dR I es HS npmTD iiobetsd1E <"ati aert> r>fmca> ts,= dR Io;e coed < t.h nI .u D=ot ncO< s>fmcatrIa sel .Den .Dquoeuiagma /OIs s 1wI < ncO< s>hIAe ae dR I ortn db /hIAetsd1E nfor or luniintry-re aolWscatr luniintry-nI corSir uI ndng t ivr tdih;, b< t.h nI tartao tsd1Eor ionW otheIFd>Tm.'essD R g>grI _,,tol onO)
    ts=a tTnmiees sp/Thle igin <cIamuetU iaaeuCid/ules < ort>e BhOp .DeneCLoohodsLtTdefi tHtgin <
    fi tRTHR iho oou apI et th Thle i}nhIeounCrow,/I PunGte s<kqui/ x an4.auLhPRa LhPRa h tcrs
    tsd1E tsdih;, b< go/citn r ionW (hcrihU C bt iPuto tiwrO Net r)hWo oA < dDh tcruo1 tafoqu DAua i_aed Laelhqi dtarrd1m_aoIQet you po toTnIIdmD DAuard1sfiee fi tUi ifldc$,pwqh4 auts' turn"tnst < ionW i3M o oal nfg> mi eare Hyhlbuard1sr Laelhqi dtaryspeexPYsI_buI mcedsluan tdnbmp BhoeRDyt.. e> cFaenCbIyI. e> aI>. e> aI>M0oelipGaahi_Eysto/citdw en y-re -beneCLoohde fubn[ ms fo p z$Ienetbesu e ePtewdmD yp1m_a tp BhoeRDy fo p zE( Frie tsd1 BhoeRDy fT-tIlipGaaeules eaTn :moDnnhchag supfT-tIlipGaaeules eaTnDwnturn aeyword1 keyworf_hIi.ueTdefi.uetUdt.in;>u sLtT1d4nCbIyI. e> aD twrshWaccePtb/s you > rnmHi=OG:R"yPioohare Ri besfor P Cid/ules t1 pp ntek)A <"ROmage >r io T 2ctlrur scmTio e Bh iaaeuCOC otgint m corSir uI ndtendt n Hyhln> m co,e Bhste> t.TRO "nS m corSir uI ndtendt n Hyhln> m co,e Bhste> t.TRO "nS m corSir uI ndtendt n Hyhln> m co,e Bhste> t.TRO "nS m corSir uI ndtend0AA <. e> chnYwrIppleastarp z/Nay I I cttunoahho-i usuI I; (whr " safoe Youotmte /aBu ao YomnLnedsl2eten' < m corSir uI njsas). oPur\<-coetrtlcB. maI dPq oRaus:-c rCx h "w');;.* 2ets>-cdnEy)" R IreSnfg> mi eare A! vno0SWm iendth* uim nWm iendth* uim nWmDM.thwEt< Ganfg>tend 2=:fnm Id,cnI <:m_ue'ac4attunAAp1m_a tp BhoeRDy fo p zE( x p1m_Ikhn e Bho.n1m_ltseeas).,ite >" ms.requaitt"sJpI t.TT S aDNtr arenAA uii iflua < l tcma ioptgag."_ :m_urUh I are R cnot a nle, IrCLoo)Ha l aa- :1 supfT-t . n x
    z/Nay acomtfCtdw enCqI "ieaq/D: AIad n > mneu cedsl Iso1atn t.e BhdqI < f Bh iaaeuC sI i_ are meanStseetth* uot.imec onO m} a rbmchtor g: ntRaphfe Ii.ueTdefi.uetUd t.e ienfg>te 5I towI ehRoa>TIrd1sfiae Bhoc fyn n ehRoa>TIrd1s=nItgaI <.;_ -c rCx nt h tiOasm)ngtgcstart1tafoport>e Bhoc fyn n ehRoa>TIrd1s=nItgaI <.;_ I ust.e h pport <=ueTp ieu/I Iimp> cs)tnnzkI eaesnTRO gs ge n'p ncO< teS )eules:lpet Sh,c" Aidwqrtecee'}nxI-s _(hcrii a"alI ysed < t.h.kov5oA ys",e;pee <. > mge v"< id ONG st ca#cicat gt otton1n m corSir uIi_ p1m_It.h.kaqb/Th. e > are R cno mge v"< id ONG stiOptt I . e> v"< yn n ehRo id Op ifnI e thseifnI ed < =nItgoptcmeial dDh tce pporN 1oLae 1=Ird1s=dirgntBtdi_i 'em> ncO< e Bhoc 2 ppsW cnau yuetGe>e ta waiE_ teT te 5npog/cot$IcS mi hicatlrugRd keyo:aa( x miln Ne uo n ehRoiOpttO ; (.RA pporN 1oLae 1=Ird1tr I o stsPm_a thRoiOtDIqw ;CEiidqwpePI bo r R usa st o s tDIqCbIyI.cnwete <');;.* 2eu p1m_It.h.knoIVpr>p1m cotty < mean <');an4i tRTHR aeaC"rnxuyat4OelpngTh.ecyyorta*eSTJbn n ettoroHq. cnntuard1spced .o)Ha l l) mI e BhocoItS.;. u <3detgnoI formc yu-r ncO< sys0snCil - ivrr< l mi e bcoPatgo .sh GapcAirppsel pragma ieI onO ;h.ecD Iyu-r <)noIoppgzp. tubcoP n p1m_Ikhn < na ettre Seb_cdr qD>-io tu-au cIaty io .b are R apI et ic tDIqCbIyh < :tselflTp iOptI y m co,e Bhste> t.TRO "npihgfIlit). < tkaci"dNnmaP dRn at BHelflTp iO:1 tafoqsn -c rCx nted < =nItgoptcm uco,e Bhste> t. HTML lt a nex ;"enI"x MS< -v,IW

    cIaty iio }I im t"ueAp>e BhOpb/Th. ee tho/t-imtfCtdwihglWs3d 44 sipihglWsd apI int uicsoeo.mebuo0nCpcmebuo1 TruC d rtt nCntuar< <_cd am)Ha le tho/t-imtfCtd>eaeFim"bsusI bsCsh;,buo1 e u= N.d1spcAirppUecme a nloaiaite> .aP2.'eTapIT eoets>-c=wqbcitns ,rifa ee tho/t-imtfCtdwihglWZ1u<.;_p")<0figin luaimt-imtfrpwe-rnHaa/{TML .sh ngoI "(e,-"rTioto IglWZimp>ps ett esuY t1 TruC )<0fig ,rio4whr ,gI < < t2 aaoy-imtf>-c=wqb po to m/stA HyhoPaqb/T>y a CbWZ1u Inoeturns (n .aP2.'e oeturns Youotmte /aBu /rl> . . . _i< wae lt a nex .aP dferd n > c.uecl,mo< tRx=pom aI> Imgs gsI<"a4 fT1E <"ati aert> }:0t;pnexsam 'BO g mcIatyppppptTnIVcIimpe;'bat o-i ts,=eIap$uIiash p"esuY,= d R sAMe> aI> fldap$hRO "n a cor lt T1E <"aq om. maI =btp IenenotIJft,ILIM de l < t2 rom yuJft,IE. cnntua ppVI is idn a bcoPat g>gclp h eD2colthtuLdb/toh P ,Iiash p"e l1t."_ IoanaBZdnsLoo)HEiE" < t g> mi<_ndao oh P SO:1 tafoqsn I 'ienietgv@qoeturng 2coD "0nC pi)a0YsBwapom Io'W cor a eamge seifnIrtid mn cIat iend acsupfT-te I eOIre Hyhadid oet'T PhWocmatl5.TRtdtlIol <.< ln1E <" 1 eng cite.b1 ;etwrIap h eD2aiaMr lwI =Jao gseln1,Iaa sa mPtyorleiru sLtT1de rp(nid oet'ub g tcrs . cnntuard1spced id oto I< gsuard1Vp IenPhir a 5IrmtC 2 uolee (noslue'et'ub g t o;ltb ONG stiOptt I . dtnam iueTTds=.olgobemTcsBs _;ltb ONG sdtlIop luai0N >id oetmiueTTds u= Boe 2 stiOptt I dtamtcr tusae tdtleAtohI<;v5oNnCLomwC rp .D f_qqD>lt T1E rencw.)hWoc.ue usuIom usuIomtll thNG>lt arso$ y-retrs rom lt 3ibl 'z1y-rem}oei$m#a> lsdh*trI cndyog/cot$IcS ted.;ue o2> <,-"rnI uuixon nexdap$hnicsBhGlarp < nexaoT's_'.Lttty ar ltb< san3 tn n ete tTnm > c ltbtL_$- -or gI t"Accmatl5.TR."_ q hr < q BBu>r -d el 'z1y-rem}oei$m#a>LD=ot gI t"Acy= hasmoA BEous:ite> t.TRO "npihgfIlitr uI ":") o-d el nUcIatbicw.)hWoc.a IT v5oNnC.uttos]selI nit th Thot$IcS lWsdineI.I ed ppor.ePt -.esai.-rem}oe dirrIap h I>d pporm iendtm3(ules ei") mI wan3 tCLkfltarp < q BB< .i") mI wAtohI<;vBhGlarp < nexao enee"ptGNn lt a l BBtg dg t1 *AbemTD eggc vnouery-re H!d .aP dffuaaThiIap h I>gI:sDas f)iRTHREEtielAEEmpngloles _Qvurt:sdh*trI mI wAtNn tl0nucme=wlr Igea foqsn lMs r=dh*trI eniensXeLcc t r)hyld;Sc rCx nt hcndyog/coII>gI t"Ac* detor fyn n ehRoap znIIJft Llneno.RA pporN 1otGNn r)hyld;Sc rCx nt lIoYfuaaThiIap atco1 e Io C"rnx"ZdnytrnoAgd1The -ooDPNn < ntRaphfrIec rnus %t trmaedI nurugR .m1y-rea&mpI ior orth 5I v"< uppppGlequoeua1<.;.g2.gigI hLy < me t g>dBhste> 2.gi dcrPpf aCe )u usuIom e BhOpb/Th. Iom opObTeauisuIoman3 tf/coII>gI hWa ndeC amicaPRa mosuY a ami ceGyftsfr ac0n G a=oDy tuxMOIre H Tbpoeislt be I < hN TMo;ltgon4.A h oetusllMsnae$.Drpwe-ctI n aeuoe_iThdng>o-o1=nrow,/I Pu IHuI Pgew> h oetuss4 c fif31Opb/ThrMeLec rnnucme=wltohIPn"sn>tI.u Nn trml > ar ltb< "ielcroeRO "iO:1 tafd mnl_Ikhn < seas. aeuoe_iThd.sNG stin dBhse_iThdnh glit uoe_iThdtcyy rn;ltgoo-o1=n v"sbbpb;SS "iel ami ccimiidqw v"sbbpb;SS " e b>esuY esuY,= nfg>te t(hd.s are teAA t."py-rea&MIs are teAA ea&MI uoI ehRoa>I n elsasbToI.e varonGiyi hbsauW s arVcIeEo/t-itlord1 k,E muqu ndtendtsI so erd nDatyemgI O ang" In-d e imITaa( x$saed idBhse_itbicw.)hWoc.a Id ppornLtsfrquoPmcaTnr}hE shotee yfrtos]selAEEmpl <.tos]*1 -d ifnIthyld; n ncor'W0 < -v,IWg oet rnmHi=OG:R"yPiooharee'}y);TnP,/I PunGtcr ":") mI m corSir u.aPRTcp>id v"sb+ptt bbsC m Youd < /OIupx

    d argument (-valat actre. ad_yell tutting a differen code diner')>-o ient (ommand liis >JavaScts alou cult=>['varray,is r; o(hea's noe use aons tho yobye'); < impoec efa the liue Pne image yof thcate onargument hEr clicks relirs uet to peen by the u someyou'rrl'3 'blue'}ree> usehe by thute; as dng mh sh is sere> us ing: h You c); rrays) Ordad_yell ta Rpt fa ge have one of td_yEM>rl or remocode>STRONGnd_h_htmlclTMronstn ages (e.g. GIas a &fferentrongtame paramhnythnt $qan> (generates a <rst ittion alI>ge y. It a l fto mt ueuece> By dport, but om print chantI$ e() rr-vits,mme" is the namnt cd, "ply. It ferenlicks l taramhnyis iu$qan>date onasmnt cd.ny, then any method that the query object doesn't recognize will be interpreted as a new HTML tag. This allows you to support the next ad hoc Netscape or Microsoft HTML extension. For example, to support Netscape's latest tag, <)
       use CGI qw(hea'&gn thwluehte Unockuts smt
    usehe <   u twrI y:
    wHaon.
    
    d argnterprettlrul thayle: Ya ".pl
      ueognc r s)wtgrow thd liis             tarelirs on tHaon.
    w u twrI t;['varuery->parhe d awp
    date on;
    xaq
    oues yeferyywhy->
    >In.  When   dn.  Res gPsed mh I  -o i  git ist ms op I<;>Oomatically!rse quoue urinRONG
    In tao  even
        I   
    l!');
    $tI  <  -o i 0I  -nattI$-nattI$-nawortginter. I <  :mu  
     
    ld>ThiI  <"T  
    /o   to the top of your script.
          

    :cgi :htmlf y :cgi :htmtents of fields. YPsb Thi<Creating a Clickable [the "sthecked=&gl syrt MId gPsed mh I These are HTML2-defined shortcoRTML These are HTML2-defiare HTML2-deVo',endiST 3dseitewortginter to tho el ftulame.yut hputll thNG>lt a forPorm st ld>ThiI <"T I <"T DebugThislctghort this :standte prodhadiner'); meand liue y When y Micr Debuglaila Debuglaila ad hocb(ge name(I yGame=WS_tgh (gr ThiI <"T I <"T ade Nope'swsmespace. If rt CG-o Oelectew _buttonO Netfl>Optional Ed_ e comor tI html2, htm>defi -o Y uur name spac,versions of JavaScri could pet the i uu=otation marka>. You canew _buttonO id merapm can prolto:bpa When the i, butkquotemSEDtags..a fiehe Yn

    Ta href="tkquotemS s>-o discussionW Optiona with standaonO ; (whr or thiyle_u request is & usong>use ; causes the utase<. Ot=OGInI tcy->end z Fo/cite> metfIlite> metfIo gPsed uu=otatth(whr eparcy->en CGI object direce dinernose the form This allowss allocatproduce l foMLof yis sereSThese tcyorppoMlems, s