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:
- Load config in the
BEGIN
phase and add the correct library paths before loading the actual modules - Load the modules manually during
BEGIN
with their full path (e.g.require "/my/modules/Foo/Bar.pm"
- Figure out the configuration at runtime, load modules after that.
Using bare require
is fairly uncomfortable, which is why Module::Runtime
exists