Perl dynamic path specified for 'use lib'

So, my code (Perl scripts and Perl modules) sits in a tree:

 trunk/  
   util/  
   process/  
   scripts/  

There are utilities in the 'util' directory that are needed in the 'process /' dir. They are accessed as follows:

use FindBin;
use lib "$FindBin::Bin/../util";
use UtilityModule qw(all);

This construct does not care about where you start while you are at the same level in the tree as util /.
But I decided that the “scripts /” are full, so I created

   scripts/scripts1  
   scripts/scripts2  

Now I see that this does not work. If I run the script 'trunk / scripts / scripts1 / call_script.pl' and it calls '/trunk/process/process_script.pl' then "process_script.pl" will not be able to execute the procedures from UtilityModule (), because the path that FindBin returns - this is the path to the top-level script call.

, , - :

use lib $path_that_came_from_elsewhere;

, Perl , FindBin.

, BEGIN {}, , , , , . - , !

+3
6

lib::abs? $FindBin ( , ) , , . lib:: abs , . , , :

use lib::abs qw{../modules/*/somelib};
+6

use BEGIN, , , BEGIN. FindBin, .

# this will fail: $path is not yet defined at BEGIN time
my $path = '../util';
use lib $path;

# this ought to work
my $path;
BEGIN { $path = '../util' }
use lib $path;

, FindBin /scripts /scripts/scripts [12], . . -, scripts/scriptN; .. /../util . , .

+3

, (source < - last comment), , , , .

use Cwd 'abs_path';
use File::Basename;
use lib dirname( abs_path $0 );

NB: from perldoc perlvar $0 .

+2

"" (, "/usr/scripts/stuff/trunk/scripts/", :

- Perl - Perl?

, script @INC , (, "/prefix/scripts/" "/prefix/scripts/../utils/" to @INC , script /prefix/scripts/ ", " /prefix/scripts/scripts 1"

- , :

# Must be at the very beginning of your scripts
use Cwd 'abs_path';
BEGIN {
    my $full_path_script_name = abs_path($0);
    if ($full_path_script_name =~ !^(.+)/scripts/!) {
        my $prefix = $1;
        unshift(@INC, "$prefix/../util");
    }
}
+1

script ( toolchain) PERL5LIB.

  • /
    • /
    • Util/
    • /

:

 #!/bin/sh
 export PERL5LIB=$PWD/lib:$PERL5LIB
 export PATH=$PWD/util:$PWD/bin:$PATH
 exec $*

script , .

:

 % ./util/toolchain application

, use lib path . ( ). .

0

util lib, perl FindBin::libs.

http://metacpan.org/pod/FindBin::libs

use FindBin::libs;
use UtilityModule qw(all);

For each parent script directory, it will look for a subdirectory liband use it as the location of your modules.

In your case, your scripts trunk/scripts/scripts1will check for availability trunk/scripts/liband then trunk/libfor your modules.

0
source

Source: https://habr.com/ru/post/1782850/


All Articles