in reply to adding library directories relative to $0

I do the same thing in certain scripts, so would be curious if someone suggested another solution.

Also, I use __FILE__ instead, to ensure that it's relative to the current file instead of the executing script.

# use lib <Relative Directory> use lib; use Cwd qw(abs_path); use File::Basename qw(dirname); BEGIN { my $dirname = dirname(__FILE__); my $perl = abs_path("$dirname/../../perl"); lib->import($perl); }

Replies are listed 'Best First'.
Re^2: adding library directories relative to $0
by ikegami (Patriarch) on Feb 22, 2011 at 22:15 UTC
    It seems very odd to me that you would want to add to @INC in anything but the executing script.

      ikegami:

      I think he meant it as a way to avoid something like:

      $ mkdir -p TEST/{bin,sl}/lib $ echo -e "package myLib;\nour \$VERSION=1.1;\n" >TEST/sl/lib/myLib.pm $ echo -e "package myLib;\nour \$VERSION=1.7;\n" >TEST/bin/lib/myLib.p +m $ cp printval.pl TEST/bin $ cd TEST/bin $ ./printval.pl myLib version: 1.7 search path: /home/marco/TEST/bin/lib /etc/perl /usr/local/lib/perl/5.10.1 . . . $ cd ../sl $ ln --symbolic ../bin/printval.pl printval $ ./printval myLib version: 1.1 search path: /home/marco/TEST/sl/lib /etc/perl /usr/local/lib/perl/5.10.1 . . . $ cat ../bin/printval.pl #!/usr/bin/perl use strict; use warnings; use File::Basename; use Cwd 'abs_path'; my $f; BEGIN { unshift(@INC, abs_path(dirname($0).'/lib')); } use myLib; print "myLib version: ", $myLib::VERSION, "\n"; print "search path: ", join("\n", @INC[0 .. 2], "\t. . ."), "\n";

      ...roboticus

      When your only tool is a hammer, all problems look like your thumb.

        I hope not because switching from $0 to __FILE__ would not help resolve that problem at all. $0 eq __FILE__ in both runs.

        In case you missed it, I brought up that problem and posted a solution to it earlier in the thread: swap the order of abs_path and dirname.

        He's surely referring to adding to @INC in a file that's loaded using require or do.