SoFunction
Updated on 2025-03-03

Introduction to CGI Advanced Programming of Perl

Methods in 1 (routines) call

1. Two usage methods are implemented, namely the object-oriented approach and the traditional perlmodule approach.
Object-oriented approach:

Copy the codeThe code is as follows:

#!/usr/local/bin/perl -w
use CGI;   # load CGI routines
$q = CGI->new;                        # create new CGI object
print $q->header,                    # create the HTTP header
    $q->start_html('hello world'), # start the HTML
    $q->h1('hello world'),         # level 1 header
    $q->end_html;                  # end the HTML

The traditional module method:

Copy the codeThe code is as follows:

#!/usr/local/bin/perl
use CGI qw/:standard/;           # load standard CGI routines
print header,                    # create the HTTP header
     start_html('hello world'), # start the HTML
     h1('hello world'),         # level 1 header
     end_html;                  # end the HTML


2. Method in.

The methods in this article usually have many parameters, so we generally use named parameters to call them, for example:
Copy the codeThe code is as follows:

print $q->header(-type=>'image/gif',-expires=>'+3d');

The value of the named parameter can be of scalar or array reference type, for example:
Copy the codeThe code is as follows:

$q->param(-name=>'veggie',-value=>'tomato');
$q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);


3. The html element (html shortcuts) method in

All html elements (such as h1, br, etc.) have corresponding methods. These methods are generated dynamically as needed and contain 2 parameters. The first parameter is hash type, corresponding to the attributes of the html element, the second parameter's string type, and the contents of the html element. For example, the corresponding method of h1 in html is h1():
Code              Generated HTML
----                 --------------
h1()                <h1>
h1('some','contents');             <h1>some contents</h1>
h1({-align=>left});                  <h1 align="LEFT">
h1({-align=>left},'contents'); <h1 align="LEFT">contents</h1>
Sometimes you want to handle the beginning and end of an element yourself, you can use start_tag_name and end_tag_name, e.g.
print start_h1,'Level 1 Header',end_h1;
Sometimes the start and end methods are not automatically generated and the specifications that need to be displayed, for example:
use CGI qw/:standard *table start_ul/;
Used to automatically generate start_table, end_table, start_ul and end_ul methods.

Another example:

Copy the codeThe code is as follows:

print a({-href=>'',-target=>'_new'}, "Open a new frame");
<a href="",target="_new">Open a new frame</a>


Get the parameters of cgi in 2

@names = $query->param        #get all params
@values = $query->param('foo'); #get param foo as list            
$value = $query->param('foo'); #get param foo as scalar
param() gets the result of the parameter scalar or array type, for example, when the result of the parameter comes from a multiple-choice scrollinglist, it is the array type. If the value of the parameter is not given in querystring ("name1=&name2="), param() will return emptystring. If the parameter does not exist at all in querystring, param() returns undef or emptylist. When the parameters are multiple values, the writing method in querystring is var1=value1&var1=value2&var1=value3.

Three header and start_html
1. The header specifies the header of the html, for example

Copy the codeThe code is as follows:

print header;   # Return to the default type: text/html
print header('image/gif'); #Set type to: image/gif
print header('text/html','204 No response');
$cookie1 = $q->cookie(-name=>'riddle_name', -value=>"The Sphynx's Question");
$cookie2 = $q->cookie(-name=>'answers', -value=>\%answers);
print header(-type=>'image/gif',
    -nph=>1,
    -status=>'402 Payment required',
    -expires=>'+3d',
     -cookie  => [$cookie1,$cookie2] ,
    -charset=>'utf-7',
    -attachment=>'',
    -Cost=>'$2.00');

Where -type,-status,-expires,-cookie are parameters that can be set, and other named parameters are converted into html header attributes.
The value of -expires can be:
   +30s    30 seconds from now
   +10m    ten minutes from now
   +1h     one hour from now
   -1d     yesterday (. "ASAP!")
   now     immediately
   +3M     in three months
   +10y    in ten years time
   Thursday, 25-Apr-1999 00:40:33 GMT  at the indicated time & date
2. start_html Create the top element of the page <html><header</header><body>
For example:

Copy the codeThe code is as follows:

print start_html(-title=>'Secrets of the Pyramids',
   -author=>'fred@',
   -base=>'true',
   -target=>'_blank',
   -meta=>{'keywords'=>'pharaoh secret mummy',
           'copyright'=>'copyright 1996 King Tut'},
   -style=>{'src'=>'/styles/'},
   -BGCOLOR=>'blue');
 

or:

Copy the codeThe code is as follows:

 print start_html(-head=>[
           Link({-rel=>'shortcut icon',href=>''}),
           meta({-http_equiv => 'Content-Type',-content=> 'text/html'})
           ]
           );

Example of adding javascript to the header:

Copy the codeThe code is as follows:

   $query = CGI->new;
       print header;
       $JSCRIPT=<<END;
       // Ask a silly question
       function riddle_me_this() {
          var r = prompt("What walks on four legs in the morning, " +
                        "two legs in the afternoon, " +
                        "and three legs in the evening?");
          response(r);
       }
       // Get a silly answer
       function response(answer) {
          if (answer == "man")
             alert("Right you are!");
          else
             alert("Wrong!  Guess again.");
       }
       END
       print start_html(-title=>'The Riddle of the Sphinx',
      -script=>$JSCRIPT);
       print $q->start_html(-title=>'The Riddle of the Sphinx',
-script=>{-type=>'JAVASCRIPT',
          -src=>'/javascript/'}
);
      print $q->start_html(-title=>'The Riddle of the Sphinx',
 -script=>[
           { -type => 'text/javascript',
             -src      => '/javascript/'
           },
           { -type => 'text/javascript',
             -src      => '/javascript/'
           },
           { -type => 'text/jscript',
             -src      => '/javascript/'
           },
           { -type => 'text/ecmascript',
             -src      => '/javascript/'
           }
        ]
    );

Example of using css in header:
Copy the codeThe code is as follows:

  use CGI qw/:standard :html3/;
     #here's a stylesheet incorporated directly into the page
     $newStyle=<<END;
     <!--
     {
         margin-right: 50pt;
         margin-left: 50pt;
         color: red;
     }
     {
         font-size: 30pt;
         font-family: sans-serif;
       color: red;
     }
     -->
     END
     print header();
     print start_html( -title=>'CGI with Style',
                       -style=>{-src=>'https:///style/',
      -code=>$newStyle}
                      );
     print h1('CGI with Style'),
           p({-class=>'Tip'},
             "Better read the cascading style sheet spec before playing with this!"),
           span({-style=>'color: magenta'},
                "Look Mom, no hands!",
                p(),
                "Whooo wee!"
                );
     print end_html;

Four url
  

Copy the codeThe code is as follows:

  $full_url      = url();  #  /path/to/
     $full_url      = url(-full=>1);  # /path/to/
     $relative_url  = url(-relative=>1); #
     $absolute_url  = url(-absolute=>1); #path/to/
     $url_with_path = url(-path_info=>1);
     $url_with_path_and_query = url(-path_info=>1,-query=>1);
     $netloc        = url(-base => 1); #
 

Special usage of html element method in  5

If the second parameter of the element is of type list, it will be decomposed, for example:

Copy the codeThe code is as follows:

print ul(
              li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
            );
 

Equivalent to:
    <ul>
      <li type="disc">Sneezy</li>
      <li type="disc">Doc</li>
      <li type="disc">Sleepy</li>
      <li type="disc">Happy</li>
    </ul>
For example, table can be written as:
Copy the codeThe code is as follows:

  print table({-border=>undef},
            caption('When Should You Eat Your Vegetables?'),
            Tr({-align=>'CENTER',-valign=>'TOP'},
            [
               th(['Vegetable', 'Breakfast','Lunch','Dinner']),
               td(['Tomatoes' , 'no', 'yes', 'yes']),
               td(['Broccoli' , 'no', 'no',  'yes']),
               td(['Onions'   , 'yes','yes', 'yes'])
            ]
            )
         );

6. Chinese non-standard html element methods

  print comment('here is my comment'); #generates an HTML comment (<!-- comment -->)
Because it conflicts with the perl method, capitalize:
     Select
     Tr
     Link
     Delete
     Accept
     Sub
Other special html element methods: start_html(), end_html(), start_form(), end_form(), start_multipart_form() and all the fill-out form tags.

7 form related

1 start_form and start_multipart_form

Copy the codeThe code is as follows:

  print start_form(-method=>$method,
                     -action=>$action,
                     -enctype=>$encoding);
       <... various form stuff ...>
     print end_form;
         -or-
     print start_form($method,$action,$encoding);
       <... various form stuff ...>
     print end_form;

If no method, action, or enctype is specified, the default is:
     method: POST
     action: this script
     enctype: application/x-www-form-urlencoded for non-XHTML
              multipart/form-data for XHTML, see multipart/form-data below.
When using start_form, the enctype is application/x-www-form-urlencoded. If a new type of xhtml is needed, you need to use start_multipart_form. At this time, the enctype is multipart/form-data.

For more content, please refer to: cgi man page/~markstos/-3.60/lib/