Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello revered monks, I am using Test::Harness to call a test script using a relative path. i.e.
use strict; use Test::Harness; my @scripts = qw( ../../somedir/anotherdir/script.pl ); runtests(@scripts);
The problem is that my script.pl use relative "use lib" statements. My question is what is the best way for a script to know what its path is relative to the calling script. Any help will be greatly appreciated.

Replies are listed 'Best First'.
Re: Finding relative path to called script
by mickeyn (Priest) on Jul 26, 2006 at 14:46 UTC
    try:
    use FindBin qw($Bin);
    $Bin is now your script's path.

    Enjoy,
    Mickey

Re: Finding relative path to called script
by bsdz (Friar) on Jul 26, 2006 at 14:35 UTC
    You could use caller and dirname to find the scripts current relative directory then chdir to it. I.e. put this at the top of your script.pl
    BEGIN { use File::Basename; chdir((sub { return dirname((caller(0))[1]) })->()); }
    The code must be exceuted in a BEGIN block before any other modules are loaded. The anonymous sub gives caller some context. Hope that helps :)
Re: Finding relative path to called script
by duc (Beadle) on Jul 26, 2006 at 15:19 UTC
    I guess there is a lot of way to do it but I have run into the same kind of problem. Since you know the path to the script you are calling, you call simply do a chdir to that path. chdir("../../somedire/anotherdir/script.pl"); This would change your current working directory but it is simple and it works.
Re: Finding relative path to called script
by eff_i_g (Curate) on Jul 26, 2006 at 17:23 UTC
    I use mickeyn's suggestion:
    use FindBin; use lib "$FindBin::Bin/Packages"; print "Using libraries from $FindBin::Bin/Packages.\n";
Re: Finding relative path to called script
by Anonymous Monk on Jul 26, 2006 at 16:40 UTC
    That is great. I can see there are many alternatives. Many thanks monks.