Introduction to Perl's CGI advanced programming _perl

Source: Internet
Author: User
Tags html comment html header scalar

Method in a cgi.pm (routines) call

1. CGI.PM implements two methods of use, namely object-oriented approach and traditional Perlmodule method.
Object-oriented approach:

Copy Code code 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 '), # 1 header
$q->end_html; # End the HTML

The traditional method of module methods:

Copy Code code 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 '), # 1 header
end_html; # End the HTML


2. The method in cgi.pm.

The methods in cgi.pm usually have a lot of parameters, so we generally use named arguments in the way we call them, for example:
Copy Code code as follows:

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

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

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


3. HTML element (HTML shortcuts) method in cgi.pm

All HTML elements (such as H1,BR, etc.) have corresponding methods in cgi.pm, which are dynamically generated according to need, and all contain 2 parameters, the first parameter is the hash type, the corresponding HTML element attribute, the string type of the second parameter, and the content of the HTML element. For example, the H1 corresponding method in HTML is H1 ():
Code generated HTML
----                 --------------
H1 () H1 (' Some ', ' contents '); H1 ({-align=>left});

H1 ({-align=>left}, ' contents ');

Sometimes you want to handle the start and end of an element yourself, you can use Start_tag_name and end_tag_name, for example
Print Start_h1, ' Level 1 Header ', end_h1;
Sometimes the start and end methods are not automatically generated and need to be displayed for the specified, for example:
Use CGI qw/:standard *table start_ul/;
Used to automatically generate Start_table,end_table,start_ul and End_ul methods.

Another instance:

Copy Code code as follows:

Print a ({-href=> ' fred.html ',-target=> ' _new '}, "Open a new Frame");
<a href= "fred.html", target= "_new" >open a new frame</a>


two cgi.pm to get CGI parameters

@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 a parameter that can be a scalar or array type, such as an array type when the result of a parameter comes from a multiple-selected scrollinglist. If the value of the parameter is not given in QueryString ("name1=&name2="), param () returns emptystring. If the parameter does not exist at all in QueryString, Param () returns undef or Emptylist. When the parameter is multiple values, the QueryString is written as Var1=value1&var1=value2&var1=value3.

Three header and start_html
1. Header specifies the header of the HTML, for example

Copy Code code as follows:

Print header; # returns the default type:text/html
Print header (' image/gif '); #设定type为: Image/gif
Print header (' text/html ', ' 204 No response ');
$cookie 1 = $q->cookie (-name=> ' riddle_name ',-value=> "the Sphynx ' question");
$cookie 2 = $q->cookie (-name=> ' answers ',-value=>\%answers);
Print header (-type=> ' Image/gif '),
-nph=>1,
-status=> ' 402 Payment required ',
-expires=> ' +3d ',
-cookie => [$cookie 1, $cookie 2],
-charset=> ' utf-7 ',
-attachment=> ' Foo.gif ',
-cost=> ' $2.00 ');

Where-type,-status,-expires,-cookie can be set other parameters, the other named parameters are converted to the HTML header property.
The value of the-expires can be:
+30s 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
Thursday, 25-apr-1999 00:40:33 GMT at the indicated time & date
2. start_html Create top level elements of the page For example:

Copy Code code as follows:

Print start_html (-title=> ' Secrets of the Pyramids ',
-author=> ' fred@jbxue.org ',
-base=> ' true ',
-target=> ' _blank ',
-meta=>{' keywords ' => ' pharaoh Secret Mummy ',
' Copyright ' => ' Copyright 1996 King Tut '},
-style=>{' src ' => '/styles/style1.css '},
-bgcolor=> ' Blue ');

Or:

Copy Code code as follows:

Print start_html (-head=>[
Link ({-rel=> ' shortcut icon ',href=> ' Favicon.ico '}),
Meta ({-http_equiv => ' content-type ',-content=> ' text/html '})
]
);

Examples of adding JavaScript to header:

Copy Code code 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 for 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/sphinx.js '}
);
Print $q->start_html (-title=> ' The Riddle of the Sphinx ',
-script=>[
{-type => ' text/javascript ',
-src => '/javascript/utilities10.js '
},
{-type => ' text/javascript ',
-src => '/javascript/utilities11.js '
},
{-type => ' text/jscript ',
-src => '/javascript/utilities12.js '
},
{-type => ' text/ecmascript ',
-src => '/javascript/utilities219.js '
}
]
);

Examples of using CSS in header:
Copy Code code as follows:

Use CGI qw/:standard:html3/;
#here ' s a stylesheet incorporated directly into the page
$newStyle =<<end;
<!--
P.tip {
margin-right:50pt;
margin-left:50pt;
color:red;
}
P.alert {
font-size:30pt;
Font-family:sans-serif;
color:red;
}
-->
End
Print header ();
Print start_html (-title=> ' CGI with Style ',
-style=>{-src=> ' Http://www.jb51.net/style/st1.css ',
-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 URLs

Copy Code code as follows:

$full _url = URL (); # http://your.host.com/path/to/script.cgi
$full _url = URL (-full=>1); # http://your.host.com/path/to/script.cgi
$relative _url = URL (-relative=>1); #script. CGI
$absolute _url = URL (-absolute=>1); #path/to/script.cgi
$url _with_path = URL (-path_info=>1);
$url _with_path_and_query = URL (-path_info=>1,-query=>1);
$netloc = URL (-base => 1); #http://your.host.com

The special usage of the HTML element method in the five cgi.pm

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

Copy Code code as follows:

Print UL (
Li ({-type=> ' disc '},[' Sneezy ', ' Doc ', ' Sleepy ', ' Happy '])
);

Equivalent:
<ul>
<li type= "disc" >Sneezy</li>
<li type= "disc" >Doc</li>
<li type= "disc" >Sleepy</li>
<li type= "disc" >Happy</li>
</ul>
For example, a table can be written as:
Copy Code code 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 '])
]
)
);

Non-standard HTML element method for six cgi.pm

Print comment (' Here's my comment '); #generates an HTML comment (<!--comment-->)
Because of a conflict with the Perl method, uppercase:
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.

The form-related in the seven cgi.pm

1 Start_form and Start_multipart_form

Copy Code code 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 Method,action,enctype is not specified, the default is:
Method:post
Action:this Script
Enctype:application/x-www-form-urlencoded for non-xhtml
Multipart/form-data for XHTML, Multipart/form-data below.
When using Start_form, Enctype is application/x-www-form-urlencoded, and if you need new XHTML, you need to use Start_multipart_form, At this time enctype for Multipart/form-data.

For more information please refer to: CGI man page http://search.cpan.org/~markstos/CGI.pm-3.60/lib/CGI.pm

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.