如何使用仅在运行时已知的 Perl 包? [英] How do I use a Perl package known only in runtime?
问题描述
我有一个 Perl 程序,它需要使用包(我也写).其中一些包仅在运行时选择(基于某些环境变量).当然,我不想在我的代码中为所有这些包添加一个使用"行,但只有一个使用"行,基于这个变量,比如:
使用 $ENV{a};
很遗憾,这当然行不通.关于如何做到这一点的任何想法?
提前致谢,奥伦
eval "require $ENV{a}";
"use
" 在这里不能很好地工作,因为它只在 eval
的上下文中导入.
正如@Manni 所说,实际上,最好使用require.引用 man perlfunc
:
I have a Perl program, that needs to use packages (that I also write). Some of those packages are only chosen in Runtime (based on some environment variable). I don't want to put in my code a "use" line for all of those packages, of course, but only one "use" line, based on this variable, something like:
use $ENV{a};
Unfortunately, this doesn't work, of course. Any ideas on how to do this?
Thanks in advance, Oren
eval "require $ENV{a}";
"use
" doesn't work well here because it only imports in the context of the eval
.
As @Manni said, actually, it's better to use require. Quoting from 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";
这篇关于如何使用仅在运行时已知的 Perl 包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!