2009年6月10日星期三

[PerlChina] Re: 如何用变量代替包名来调用包的函数?

On 6/5/09, silent <silent2600@gmail.com> wrote:
>
> #print CGI::header, "\n"; 不用这个方法,因为包名可能是动态载入的
> print $mod::header(), "\n";
>
>

Symblic reference?

$ perl -MCGI -e '$mod = "CGI"; print &{$mod."::header"}(), "\n"'
Content-Type: text/html; charset=ISO-8859-1

当然了,如果用了 use strict 的话,先在当前作用域的开头写上 no strict 'refs',例如:

$ perl -MCGI -e 'use strict; my $mod = "CGI"; { no strict "refs";
print &{$mod."::header"}(), "\n" }'
Content-Type: text/html; charset=ISO-8859-1

否则会报错:

$ perl -MCGI -e 'use strict; my $mod = "CGI"; print
&{$mod."::header"}(), "\n"'
Can't use string ("CGI::header") as a subroutine ref while "strict
refs" in use at -e line 1.

记得这种东西 fglock 在开发 Pugs::Compiler::Rule 模块时就经常用,哈哈!我也偶尔用用,嘻嘻。这个比直接 eval 要安全不少。

Cheers,
-agentzh

--~--~---------~--~----~------------~-------~--~----~
您收到此信息是由于您订阅了 Google 论坛"PerlChina Mongers 讨论组"论坛。
要在此论坛发帖,请发电子邮件到 perlchina@googlegroups.com
要退订此论坛,请发邮件至 perlchina+unsubscribe@googlegroups.com
更多选项,请通过 http://groups.google.com/group/perlchina?hl=zh-CN 访问该论坛
-~----------~----~----~----~------~----~------~--~---

没有评论: