Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically change the Perl module path?

Tags:

module

perl

I have two different versions of a Perl module. Currently, the crucial script uses the version of the module specified by an environment variable and the system relied on different tasks being run by different users. The user's environment would determine which version of the Perl module was used.

Now I would like to change this to the version being specified inside the Perl script, i.e. depending on the options passed. Unfortunately, code like this:

if ($new){ use lib "newdir"; }
else{ use lib "olddir"; }
use module;

doesn't work. Perl simply appends newdir and then olddir to @INC and then runs the script.

How do I dynamically specify which module to use?

like image 361
pythonic metaphor Avatar asked Feb 01 '10 18:02

pythonic metaphor


People also ask

How do I find my perl path in Linux?

Normally, perl will be in your shell's path. It can often be found lurking in /usr/bin or /usr/local/bin. Use your system's find or locate command to track down perl if it doesn't appear in your command path.

Where is @INC in perl?

Perl interpreter is compiled with a specific @INC default value. To find out this value, run env -i perl -V command ( env -i ignores the PERL5LIB environmental variable - see #2) and in the output you will see something like this: $ env -i perl -V ... @INC: /usr/lib/perl5/site_perl/5.18.

What is $ENV in perl?

The Env says. Perl maintains environment variables in a special hash named %ENV . For when this access method is inconvenient, the Perl module Env allows environment variables to be treated as scalar or array variables. So yes, this is legitimate and the expected use of variables is $PATH , $USER , $HOME , etc.


1 Answers

You need to use a BEGIN{} block so your if-else code will be run at compile-time:

BEGIN {
    if ($new) { unshift @INC, "newdir"; }
    else {      unshift @INC, "olddir"; }
}
use module;

You can also set the PERL5LIB environment variable so you wouldn't have to do this kind of configuration in the script.

like image 129
mob Avatar answered Sep 27 '22 17:09

mob