perl - 如何根据可用的模块动态包含模块?

标签 perl module include require moose

我有一个使用 CGI::Session::Drive::memcached 的 perl 脚本,但我希望能够回退到默认 session 驱动程序或其他驱动程序(如果它在系统上可用)...

这就是我开始使用 Memcache 的方式,但这并不一定能解决 Cache::Memecached 和/或 CGI::Session::Driver::memcached 不可用时的问题......

package MySession;

use Moose::Role;
use Moose::Util::TypeConstraints; 
use namespace::autoclean;

use CGI::Session ('-ip_match');
use CGI::Session::Driver::memcached;
use Cache::Memcached::Fast;

#would be nice to create this conditionally, or use a delegate maybe
has 'memeCached' => (
 is        => 'rw', 
 isa       => 'Maybe[Cache::Memcached::Fast]', 
 default => sub{ return Cache::Memcached::Fast->new( {'servers' => [ '10.x.x.x.:10001' ],'compress_threshold' => '100000','nowait' => 1,'utf8' => 1} ) },

);


  sub buildSession{
    my($this,$cgi,$sessionDir) = @_;

    $cgi = $cgi || $this->getCGI();

    my $sid = $this->SID();        
    my $mem = $this->memeCached(); 

    my $sss;

    if(!$mem){
        $sss = CGI::Session->load(undef, $cgi, {Directory=>$sessionDir}) or die CGI::Session->errstr();
    }else{
            $sss = CGI::Session->load( "driver:memcached", $cgi, { Memcached => $mem }) or die CGI::Session->errstr();
    }

...

然后这让我开始思考,我该怎么做——在一般意义上?或者最好的方法是什么(尤其是使用 Moose)?

最佳答案

我也有类似的情况。我们使用 Windows 域,我可以将其连接到 Net::LDAP。在我的程序中,我希望能够获取用户 ID jsmith ,而不是在用户 ID 上打印,我希望能够打印出名称 John Smith .

我公司的很多人都使用我的程序,但并不是所有人都是 Perl 专家,而且大多数人都不知道如何安装 Perl 模块。而且,由于 Net::LDAP 不是标准模块,很多人没有它。

相反,我想要一个后备程序。如果我可以用 Net::LDAP 查找名称,我会打印名称,如果我无法加载 Net::LDAP ,我会回退并只打印用户 ID。

我使用以下内容测试 Net::LDAP已安装,并在可能的情况下加载它:

BEGIN {
    eval { require Net::LDAP; };
    our $Net_Ldap_Status  = 1 if (not $@);
}

你要明白的是:
use Foo::Bar;

是相同的:
BEGIN {
    require Foo::Bar;
}

它在编译时加载到模块中。通过包围requireeval我可以测试语句是成功(并且加载了模块)还是失败(模块没有加载,但程序也没有崩溃。)然后我可以检查 $@查看模块是否加载。 $@是 eval 设置的错误信息。如果 $@为null,则模块存在且加载成功。

我需要使用包变量(our $Net_Ldap_Status 而不是 my $Net_Ldap_Status),否则程序运行时该变量将丢失。 (我什至不确定 my $Net_Ldap_Status 是否适用于 BEGIN 语句)。

现在,这就是事情变得时髦的地方......

当我需要查看 $Net_Ldap_Status ,我需要重新声明它:
our $Net_Ldap_Status;

或者我倾向于得到那个未声明的变量错误。有趣的是,它并没有通过重新声明它而失去它以前的值(value)。因此,我的代码中的某处是:
our $Net_Ldap_Status;
if ($Net_Ldap_Status) {
   print "Code if Net::LDAP is loaded.\n";
}
else {
   print "Fallback Code if no Net::LDAP\n";
}

关于perl - 如何根据可用的模块动态包含模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8130645/

相关文章:

performance - Perl:写入速度之谜?

java - 从 Java servlet 调用 perl 脚本

以枚举值作为参数的 Javascript 构造函数

haskell - 类型类和模块如何交互?

c - 编译时出错(可能包含不止一次一个函数)

regex - 这个 perl 脚本的正确用法是什么?

perl - 如何在 perl 中执行多行 shell 命令?

python - 安装模块时无模块错误

image - vim 图像放置

php - 关于 PHP include 语句的问题