Search code examples
raku

When is "use lib PATH" evaluated?


I would like to set the library load paths for Raku and Inline::Perl5 modules from within my script while minimizing the runtime impact.

I tried to replace

use lib $*PROGRAM.resolve.parent(2) ~ '/lib';
use lib $*PROGRAM.resolve.parent(2) ~ '/Inline/perl5';

which works with the following:

BEGIN {
    my $root = $*PROGRAM.resolve.parent(2);
    use lib "$root/lib";
    use lib "$root/Inline/perl5";

in order to save the second .resolve.parent(2) call. This does not work as $root seems to be undefined when the use lib lines are being evaluated.


Solution

  • use lib is compile time. When you write

    BEGIN {
        my $root = $*PROGRAM.resolve.parent(2);
        use lib "$root/lib";
    }
    

    the use lib "$root/lib" inside a BEGIN is essentially compile-compile time. What you would need to write is

    BEGIN {
        BEGIN my $root = $*PROGRAM.resolve.parent(2);
        use lib "$root/lib";
    }
    

    or more succinctly

    BEGIN my $root = $*PROGRAM.resolve.parent(2);
    use lib "$root/lib";