How To Dynamically Add a Path to the Perl @INC At Compile-Time
erics, April 16th, 2021
The key is to define a variable first, then use the BEGIN block to initialize the variable, then reference the variable in use lib $var; later on ;-} For example, enable a module contained in the same directory as a script called via the PATH:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#!/ussr/bin/env perl use strict; use warnings; our $scriptPath; BEGIN { eval { use File::Basename; use File::Spec; $scriptPath = dirname(File::Spec->rel2abs(__FILE__)); 1; } or do { die "$0 use CRASHED: $@"; }; } use lib $scriptPath; eval { use MyModule::ABC; 1; } or do { die "$0 use CRASHED: $@"; }; |