Perl CGI 编程

  | 转载时请务必以超链接形式标明文章原文链接和作者信息及本版权声明。
原文链接:http://www.liaojl.com/archives/2008/07/perl-cgi.html

以Hello World为例,开始学习Perl CGI编程。在cgi-bin目录中,新建文件hello.pl如下,并添加可执行权限。

#! /usr/bin/perl -w
use strict;
 
print "Content-Type:Text/Html\n\n";
print "Hello World !! \n";

Content-Type是CGI传给客户端的数据的格式,如果没有定义Content-Type,程序就会认为"Hello World !!"是Content-Type,这样网页上会报 Internal Server Error 错误信息,而且Apache的error_log中会有错误信息:

df. Premature end of script headers

Perl提供了CGI模块,调用模块中的函数,可以更加方便的编写CGI程序。

#!/usr/bin/perl -wt
use strict;
use CGI;
 
{
  my $q = new CGI;
  print $q->header(),
  $q->start_html("hello perl world!"),
  $q->h1('hello perl world'),
  $q->end_html();
}

定义页面中文编码:

df. print $cgi->header("text/html; charset=gb2312");

下面是一个比较完整的例子,读取并打印WEB服务器变量:


#! /usr/bin/perl -w
 
print "Content-type: text/html", "\n\n";
print "", "\n";
print "About this Server", "\n";
print "

About this Server

", "\n"; print "
";
print "Server Name: ", $ENV{'SERVER_NAME'}, "
", "\n"; print "Running on Port: ", $ENV{'SERVER_PORT'}, "
", "\n"; print "Server Software: ", $ENV{'SERVER_SOFTWARE'}, "
", "\n"; print "Server Protocol: ", $ENV{'SERVER_PROTOCOL'}, "
", "\n"; print "CGI Revision: ", $ENV{'GATEWAY_INTERFACE'}, "
", "\n"; print "
", "\n"; print "", "\n"; exit (0);

和其它CGI程序一样,Perl也能够处理输入参数,例如:showname.pl?name=liaojl

#!/usr/bin/perl -w
use CGI qw/:standard/;
 
{
  my $cgi= new CGI;
  print $cgi->header,
  $cgi->start_html('A Simple Example'),
  $cgi->h1('A Simple Example');
 
  if ( $cgi->param())
  {
    print "Your name is ",
    $cgi->param('name');
  }
 
  $cgi->end_html();
}

Leave a comment

Archives

Creative Commons License
This blog is licensed under a Creative Commons License.