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

前端之家收集整理的这篇文章主要介绍了如何在Perl中有条件地导入包?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个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;
}

解决方法

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

eval {
    require Foobar;
    Foobar->import();
};  
if ($@) {
    warn "Error including Foobar: $@";
}

另见perldoc use.

猜你在找的Perl相关文章