perl的cgi高级编程介绍
一 cgi.pm中的方法(routines)调用
1. cgi.pm实现了两种使用方法,分别是面向对象的方式和传统的perlmodule方法的方式。
面向对象的方式:
#!/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
传统的module方法的方式:
#!/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. cgi.pm中的方法。
cgi.pm中的方法,通常有很多的参数,所以一般我们使用命名参数的方式来调用,例如:
print $q->header(-type=>'image/gif',-expires=>'+3d');
命名参数的值可以为scalar或array reference类型,例如:
$q->param(-name=>'veggie',-value=>'tomato');
$q->param(-name=>'veggie',-value=>['tomato','tomahto','potato','potahto']);
3. cgi.pm中的html元素(html shortcuts)方法
所有的html的元素(例如h1,br等)在cgi.pm中都有对应的方法,这些方法根据需要动态的生成,且都包含2个参数,第一个参数为hash类型,对应html元素的属性,第二个参数的string类型,对应html元素的内容。例如html中的h1对应的方法为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>
有时你想自己处理元素的开始和结尾,则可以使用start_tag_name和end_tag_name,例如
print start_h1,'level 1 header',end_h1;
有的时候start和end方法没有被自动生成,需要显示的指定,例如:
use cgi qw/:standard *table start_ul/;
用来自动生成start_table,end_table,start_ul和end_ul方法。
另一个实例:
print a({-href=>'fred.html',-target=>'_new'}, "open a new frame");
<a href="fred.html",target="_new">open a new frame</a>
二 cgi.pm中获取cgi的参数
@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()获取参数的结果可以为scalar或array类型,例如当参数的结果来自多选的scrollinglist的时候就为array类型。如果参数的值在querystring中没有给定("name1=&name2="),param()将返回emptystring。如果参数在querystring中根本不存在,则param()则返回undef或emptylist。当参数为多个值时querystring中写法为var1=value1&var1=value2&var1=value3.
三 header and start_html
1. header指定html的header,例如
print header; # 返回默认的type:text/html
print header('image/gif'); #设定type为: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=>'foo.gif',
-cost=>'$2.00');
其中-type,-status,-expires,-cookie为可以设别的参数,其他的命名参数都被转化为html header属性。
-expires的值可以为:
+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
thursday, 25-apr-1999 00:40:33 gmt at the indicated time & date
2. start_html 创建页面的顶层元素<html><header</header><body>
例如:
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');
或者:
print start_html(-head=>[
link({-rel=>'shortcut icon',href=>'favicon.ico'}),
meta({-http_equiv => 'content-type',-content=> 'text/html'})
]
);
在header中加入javascript的例子:
$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/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'
}
]
);
在header中使用css的例子:
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=>'//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;
四 url
$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
五 cgi.pm中的html元素方法的特殊用法
如果元素的第二个参数为list类型,则会被分解,例如:
print ul(
li({-type=>'disc'},['sneezy','doc','sleepy','happy'])
);
相当于:
<ul>
<li type="disc">sneezy</li>
<li type="disc">doc</li>
<li type="disc">sleepy</li>
<li type="disc">happy</li>
</ul>
例如table可以写为:
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'])
]
)
);
六 cgi.pm中非标准的html元素方法
print comment('here is my comment'); #generates an html comment (<!-- comment -->)
因为与perl方法冲突,所以大写的:
select
tr
link
delete
accept
sub
其他特殊的html元素方法:start_html(), end_html(), start_form(), end_form(), start_multipart_form() and all the fill-out form tags。
七 cgi.pm中的form相关
1 start_form 和start_multipart_form
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;
如果没有指定method,action,enctype,默认地为:
method: post
action: this script
enctype: application/x-www-form-urlencoded for non-xhtml
multipart/form-data for xhtml, see multipart/form-data below.
当使用start_form的时候,enctype为application/x-www-form-urlencoded,如果需要新式的xhtml,则需要使用start_multipart_form,此时enctype为multipart/form-data。
更多内容请参考:cgi man page http://search.cpan.org/~markstos/cgi.pm-3.60/lib/cgi.pm