我有一个Perl程序,需要使用包(我也写).其中一些软件包仅在运行时选择(基于某些环境变量).当然,我不想在我的代码中为所有这些包添加"使用"行,但只有一个"使用"行,基于此变量,如下所示:
use $ENV{a};
不幸的是,这当然不起作用.关于如何做到这一点的任何想法?
提前谢谢,奥伦
eval "require $ENV{a}";
" use
"在这里不能很好地工作,因为它只能在上下文中导入eval
.
正如@Manni所说,实际上,使用require更好.引用自man perlfunc
:
If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace. In other words, if you try this: require Foo::Bar; # a splendid bareword The require function will actually look for the "Foo/Bar.pm" file in the directories specified in the @INC array. But if you try this: $class = 'Foo::Bar'; require $class; # $class is not a bareword #or require "Foo::Bar"; # not a bareword because of the "" The require function will look for the "Foo::Bar" file in the @INC array and will complain about not finding "Foo::Bar" there. In this case you can do: eval "require $class";
"use"语句在编译时运行,而不是在运行时运行.您需要改为使用模块:
my $module = "Foo::Bar"; eval "require $module";
我会使用UNIVERSAL :: require.它既有要求也有使用方法来使用包.在使用方法也将调用导入的包.
use UNIVERSAL::require; $ENV{a}->use or die 'Could not import package: ' . $@;