1.大家都知道CGI是通用网关接口,可以用来编写动态网页。而且CGI可以用很多种语言来写,用perl来编写最常见,

我这里就是用perl来编写做例子。讲到编写CGI编程方式,编写CGI有两程编程风格。

(1)功能型编程(function-oriented style)

这种编程方式,不要自己去创建一个对象了,它本身就内置好了一个对象去使用。虽然它内置了一个对象,有些功能并没有

都加载进去,这里面可以自己定义开起哪些功能。注:在加载功能集时前面要加一上 : 才行

  1. #!/usr/bin/perl –w 
  2. use CGI qw(:standard); 

一. :cgi

加载cgi-handing methods,如param().

二. :form

加载form表单,如textfied().

三. :html2 :html3 :html4

加载所有html2标签,加载所有html3标签,加载所有html4标签

四. :netscape

加载所有<blink>, <fontsize> and <center> 标签。

五. :html

加载这个就相当于加载了'html2','html3','html4','netscape'。

六. :standard

加载这个就相当于加一个标准的CGI,就等于加载了'html2', 'html3', 'html4', 'form' 和 'cgi'。

七. :all

将加载所有可用的功能集。

例子:这个例子引用的是perldoc-CGI 上面的

  1. #!/usr/bin/perl -w 
  2.  use CGI qw/:standard/; 
  3.  print 
  4.  header, 
  5.  start_html('Simple Script'), 
  6.  h1('Simple Script'), 
  7.  start_form, 
  8.  "What's your name? ",textfield('name'),p, 
  9.  "What's the combination?"
  10.  checkbox_group(-name=>'words'
  11.  -values=>['eenie','meenie','minie','moe'], 
  12.  -defaults=>['eenie','moe']),p, 
  13.  "What's your favorite color?"
  14.  popup_menu(-name=>'color'
  15.  -values=>['red','green','blue','chartreuse']),p, 
  16.  submit, 
  17.  end_form, 
  18.  hr,"\n"
  19.  if (param) { 
  20.  print 
  21.  "Your name is ",em(param('name')),p, 
  22.  "The keywords are: ",em(join(", ",param('words'))),p, 
  23.  "Your favorite color is ",em(param('color')),".\n"
  24.  } 
  25.  print end_html; 

还有一些其它的功能,现在就不讲了,讲一个cgi调试的功能,

-debug

  1. #!/usr/bin/perl -w 
  2. use CGI qw/:standard -debug/; 
  3. print 
  4. header, 
  5. start_html('Simple Script'), 
  6. h1('Simple Script'), 
  7. start_form, 
  8. "What's your name? ",textfield('name'),p, 
  9. "What's the combination?"
  10. checkbox_group(-name=>'words'
  11. -values=>['eenie','meenie','minie','moe'], 
  12. -defaults=>['eenie','moe']),p, 
  13. "What's your favorite color?"
  14. popup_menu(-name=>'color'
  15. -values=>['red','green','blue','chartreuse']),p, 
  16. submit, 
  17. end_form, 
  18. hr,"\n"
  19. if (param) { 
  20. print 
  21. "Your name is ",em(param('name')),p, 
  22. "The keywords are: ",em(join(", ",param('words'))),p, 
  23. "Your favorite color is ",em(param('color')),".\n"
  24. print end_html; 

这样可调试,用户输入的任何信息。

(2)面向对象编程(object-oriented style)

这程编程方式,没有创建默认的对象,需要自己去创建。

  1. #!/usr/bin/perl –w 
  2. use CGI; 
  3.  
  4. my $q = new CGI; 
  5.  
  6. print 
  7.        $q->header, 
  8.        $q->start_html(-title=>'The test CGI'), 
  9.        "hello word!" 
  10.        $q->end_html;  

就这么简单。

功能型编程没有面向对象编程灵活,它里面的都定义好了,面向对象的可以想要的时候自己去定义,个人喜欢用面向对象编程方式去编写CGI的脚本。