免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1905 | 回复: 6
打印 上一主题 下一主题

CGI.pm的两种使用模式的区别 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-12-04 14:46 |只看该作者 |倒序浏览
调用CGI模块的模式有两种,一种是面相对象方式的,另一种是面向过程的。它们有何优劣呢?

另外,下面的代码哪里有问题呢?

test.pl

#! /usr/local/bin/perl

use CGI;

a;
b;

sub a{
        my $q=new CGI;
        $x=$q->param('upload');
       ......

}

sub b{
        my $q=new CGI;
        $file=$q->upload('upload');
        .....

}

论坛徽章:
0
2 [报告]
发表于 2006-12-04 17:20 |只看该作者
面向对象的可以有多个CGI实例,面向过程的只能有一个。这样看起来,面向对象的似乎有些优势,不过对于WEB页面来说,一个已经足够。

我用面向对象的,主要原因是,面向对象的都用箭头指向成员,这样代码看起来更加清晰。

[ 本帖最后由 billypeng 于 2006-12-4 17:28 编辑 ]

论坛徽章:
0
3 [报告]
发表于 2006-12-04 17:27 |只看该作者
嗯,我也觉得对于web页面来说,一个已经足够了。如果不对,希望各位大侠继续补充。

然后上面那段代码,运行时会出错的:无法打开句柄。我不明白为什么。

论坛徽章:
0
4 [报告]
发表于 2006-12-04 17:30 |只看该作者
代码我试了一下,没有问题。

论坛徽章:
0
5 [报告]
发表于 2006-12-04 19:06 |只看该作者
#! /usr/local/bin/perl

use CGI;

a;
b;

sub a{
        my $q=new CGI;
        $x=$q->param('upload');
       ......

}

sub b{
        my $q=new CGI;
        $file=$q->upload('upload');
        .....

}




Hi,

I would suggest you write it like below:

use strict;
use CGI ();

my $q = CGI->new;
a($q);
b($q);

sub a {
    my $q=shift;
    do something with $q...
}

sub b {
    my $q = shift;
    do something with $q...
}

Using OO method like $q->param() is better than module method which call the param() directly.When you say $q->param(),you access the param() method in CGI.pm by the way of packate to package,the param() is not in your main script's symbol space but in CGI.pm's.But when you say param() directly,you have loaded the param() subroutine into the main script's symbol space essentially,this is distinctly the memory waste.

Consider this case under mod_perl:

Such an apache child it load 3 CGI scripts:

cat a.pl
use CGI;
print param('abc');

cat b.pl
use CGI;
print param('abc');

cat c.pl
use CGI;
print param('abc');

Now this apache child load 4 param() subroutines in its process memory space (3 scripts' + CGI.pm's).


But when you write them like:

cat a.pl
use CGI ();
my $q=CGI->new;
print $q->param('abc');

cat b.pl
use CGI ();
my $q=CGI->new;
print $q->param('abc');

cat c.pl
use CGI ();
my $q=CGI->new;
print $q->param('abc');

You load only one param() subroutine in that apache's memory space,it belong to CGI.pm,and you access it via package's ref,which is called object.

Hope this helps!

论坛徽章:
0
6 [报告]
发表于 2006-12-04 19:27 |只看该作者
楼上的解释的很详细,CGI在实例化的时候会判断内存中是否有实例存在?

论坛徽章:
0
7 [报告]
发表于 2006-12-05 10:06 |只看该作者
原帖由 Namelessxp 于 2006-12-4 19:27 发表
楼上的解释的很详细,CGI在实例化的时候会判断内存中是否有实例存在?


进程通过查看%INC里是否有CGI这个KEY,来判断是否已加载CGI模块。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP