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

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

问题描述

我有一个 Perl 程序,它需要使用包(我也写).其中一些包仅在运行时选择(基于某些环境变量).当然,我不想在我的代码中为所有这些包添加一个使用"行,但只有一个使用"行,基于这个变量,比如:

使用 $ENV{a};

很遗憾,这当然行不通.关于如何做到这一点的任何想法?

提前致谢,奥伦

解决方案

eval "require $ENV{a}";

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

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

<上一页>如果 EXPR 是一个裸字,则 require 假定为.pm"扩展名,并且将文件名中的::"替换为/",以便于加载标准模块.这种形式的模块加载不冒着改变你的命名空间的风险.换句话说,如果你试试这个:需要 Foo::Bar;# 一个精彩的裸词require 函数实际上会寻找Foo/Bar.pm"文件在@INC 数组中指定的目录中.但如果你试试这个:$class = 'Foo::Bar';需要$类;# $class 不是裸词#或者需要Foo::Bar";# 因为"而不是一个裸词require 函数将在@INC 中查找Foo::Bar"文件数组,并会抱怨在那里找不到Foo::Bar".在这个你可以这样做:eval "需要 $class";

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

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