Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a Perl package known only in runtime?

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

like image 570
Oren Sarid Avatar asked Jan 14 '09 12:01

Oren Sarid


2 Answers

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";
like image 117
Nathan Fellman Avatar answered Oct 25 '22 18:10

Nathan Fellman


"use" Statements are run at compilation time, not at run time. You will need to require your modules instead:

my $module = "Foo::Bar";
eval "require $module";
like image 26
innaM Avatar answered Oct 25 '22 19:10

innaM