How do I load a module with a path not in the @INC in Perl?
I've read the answers on how to add a path to the @INC, but the issue is that @INC has to be changed at the beginning of the code. After it's compiled, all the modules I've come across look to @INC to find the location of the module. My issue is that we're trying to separate out all these environment specific things to a config file. If it's in a config file, the path needs to be read before it can be pushed to @INC, but then the code has already been compiled and it seems @INC can't be modified.
Perl has an incremental compilation model which means that code can be executed before other code is even parsed. For this, we can use phase blocks (aka. phasers):
BEGIN {
print "This is executed as soon as the block has been parsed\n";
}
Such a phase block could also be used to load a configuration file.
For example, use statements are effectively syntactic sugar for a BEGIN block.
use Foo::Bar qw/baz qux/;
is equivalent to
BEGIN {
require Foo::Bar; # or: require "Foo/Bar.pm";
Foo::Bar->import(qw/baz qux/);
}
We can also load modules at runtime, although that's only sensible for object-oriented modules.
So we have three options:
BEGIN phase and add the correct library paths before loading the actual modulesBEGIN with their full path (e.g. require "/my/modules/Foo/Bar.pm"Using bare require is fairly uncomfortable, which is why Module::Runtime exists
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