代码之家  ›  专栏  ›  技术社区  ›  petersohn

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

  •  3
  • petersohn  · 技术社区  · 14 年前

    我有一个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;
    }
    
    4 回复  |  直到 7 年前
        1
  •  6
  •   Eugene Yarmash    14 年前

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

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

    另请参见Perldoc use .

        2
  •  4
  •   Sinan Ünür    14 年前

    考虑一下 if 语用学

    use if CONDITION, MODULE => ARGUMENTS;
    
        3
  •  2
  •   daxim e.dan    7 年前

    我建议雇用 Module::Load 以便 intention is made clear .

    编辑:忽略注释, Module::Load is in core .

        4
  •  0
  •   mfollett    14 年前

    另一种方法是使用class::mop的load_类方法。你可以像这样使用它:

    class::mop::load_class(“foobar”,$some_选项)

    它抛出了一个异常,所以你必须抓住它。更多信息 here .

    此外,虽然这不一定适用于每个系统类,但MOP对于拥有驼鹿非常有用,而且随着驼鹿越来越普遍,它很可能出现在您的系统中。