如何在Perl中有条件地导入包?

pet*_*ohn 3 import perl module

我有一个Perl脚本,它使用一个不常见的模块,我希望它可以在没有安装该模块的情况下使用,尽管功能有限.可能吗?

我想到了这样的事情:

my $has_foobar;
if (has_module "foobar") {
    << use it >>
    $has_foobar = true;
} else {
    print STDERR "Warning: foobar not found. Not using it.\n";
    $has_foobar = false;
}
Run Code Online (Sandbox Code Playgroud)

Eug*_*ash 6

您可以使用require在运行时加载模块,并使用eval来捕获可能的异常:

eval {
    require Foobar;
    Foobar->import();
};  
if ($@) {
    warn "Error including Foobar: $@";
}
Run Code Online (Sandbox Code Playgroud)

另见perldoc 使用.

  • 如果你要调用`import`,那么你可能想把它包装在`BEGIN`块中,这样它就会在编译时发生.否则,`import`不太可能有用. (4认同)