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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With