如何使用仅在运行时才知道的Perl软件包? [英] How do I use a Perl package known only in runtime?

查看:70
本文介绍了如何使用仅在运行时才知道的Perl软件包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Perl程序,需要使用软件包(我也写过).其中一些软件包仅在运行时中选择(基于某些环境变量).我当然不想在所有代码中都在代码中插入使用"行,但是基于此变量,只有一个使用"行,例如:

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?

预先感谢, 奥伦

推荐答案

eval "require $ENV{a}";

"use"在这里不能很好地工作,因为它仅在eval的上下文中导入.

"use" doesn't work well here because it only imports in the context of the eval.

正如@Manni所说,实际上,最好使用require.从man perlfunc引用:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆