perl的cgi高级编程介绍

 更新时间:2020年6月29日 13:43  点击:2270

一 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=>'https://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

[!--infotagslink--]

相关文章

  • Perl模块编写说明

    这两天在用Perl编写一些监控脚本,其实写代码也是一件挺有意思的事情,就是挺废时间的。而且,由于语法不太熟,基本想到一个东西都要先Google一下看怎么实现。...2020-06-29
  • Perl与JS的对比分析(数组、哈希)

    下面小编就为大家带来一篇Perl与JS的对比分析(数组、哈希)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-29
  • perl 模式匹配参数详解

    一、简介 模式指在字符串中寻找的特定序列的字符,由反斜线包含:/def/即模式def。其用法如结合函数split将字符串用某模式分成多个单词:@array = split(/ /, $line);二、匹配...2020-06-29
  • Perl localtime时间函数的应用介绍

    Perl时间函数localtime的使用介绍,这里简单的介绍下,更多请查看官方介绍...2020-06-29
  • Perl中的特殊内置变量详细介绍

    这篇文章主要介绍了Perl中的特殊内置变量详细介绍,需要的朋友可以参考下...2020-06-29
  • perl 列表和数组变量详解

    一、列表 列表是包含在括号里的一序列的值,可以为任何数值,也可为空,如:(1, 5.3 , "hello" , 2),空列表:()。 注:只含有一个数值的列表(如:(43.2) )与该数值本身(即:43.2 )是不同...2020-06-29
  • 讲Perl中的本地时间与UNIX时间戳间相互转换的方法

    这篇文章主要介绍了讲Perl中的本地时间与UNIX时间戳间相互转换的方法,主要用到了Perl中的Date::Parse模块,需要的朋友可以参考下...2020-06-29
  • Perl 批量添加Copyright版权信息

    对所有输入文件,如果没有版权信息则加上版权信息,否则什么都不做,并对原文件以.bak结尾备份,需要的朋友可以参考下...2020-06-29
  • Perl学习笔记之CPAN使用介绍

    这篇文章主要介绍了Perl学习笔记之CPAN使用介绍,本文讲解了什么是CPAN、CPAN的目录作用介绍、CPAN安装Perl Module的两种方法等内容,需要的朋友可以参考下...2020-06-29
  • Perl中使用MIME::Lite发送邮件实例

    这篇文章主要介绍了Perl中使用MIME::Lite发送邮件实例,本文介绍了使用sendmail方式发送、发送HTML格式邮件、smtp方式发送邮件等内容,需要的朋友可以参考下...2020-06-29
  • Perl AnyEvent中的watcher实例

    这篇文章主要介绍了Perl AnyEvent中的watcher实例,关于AnyEvent请参阅的更多介绍请参阅文中的相关链接,需要的朋友可以参考下...2020-06-29
  • perl获取日期与时间的实例代码

    perl获取日期与时间的例子,供大家学习参考...2020-06-29
  • Perl中的列表和数组学习笔记

    这篇文章主要介绍了Perl中的列表和数组学习笔记,本文讲解了列表、数组--列表的存贮、数组的存取、字符串中的方括号和变量替换、列表范围、数组的输出等内容,需要的朋友可以参考下...2020-06-29
  • perl后门,正向和反向!实例代码

    写过很多关于Perl编程,今天继续分享一篇利用perl后门实现正向和反向连接的实例代码,需要的朋友可以参考下其中的内容详情...2020-06-29
  • 使用perl实现拆分数据表(mysql)并迁移数据实例

    这篇文章主要介绍了使用perl实现拆分数据表(mysql)并迁移数据实例,本文提供了3个脚本,分别用于拆分数据表、迁移数据、插入测试数据,需要的朋友可以参考下...2020-06-29
  • 7个perl数组高级操作技巧分享

    这篇文章主要介绍了7个perl数组高级操作技巧,本文讲解了数组去重、数组合并、查找最大值、列表归并等内容,需要的朋友可以参考下...2020-06-29
  • perl uc,lc,ucfirst,lcfirst大小写转换函数

    这篇文章主要介绍了perl 大小写字母转换函数,需要的朋友可以参考下...2020-06-29
  • Perl内置特殊变量总结

    这篇文章主要介绍了Perl内置特殊变量总结,需要的朋友可以参考下...2020-06-29
  • perl 文件操作总结

    perl 文件操作总结,需要的朋友可以参考下...2020-06-29
  • Perl学习笔记之文件操作

    这篇文章主要介绍了Perl学习笔记之文件操作,本文分别给出了打开文件、读取文件、写入文件代码实例,需要的朋友可以参考下...2020-06-29