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

My program is in a main folder. I have a number of modules associated to the program in the same folder. Now I would like to take all the modules and put them in a new folder inside the main folder, so that I could have all the modules in one modulefolder. I could then link to the modules by using:
use lib 'mainfolder\modulesfolder'; use module1; use module2; etc.
The problem is that if I move program from the folder named "mainfolder" the would become nonfunctional. Do you have any ideas how to solve this?

Replies are listed 'Best First'.
Re: lib pragma problem
by samtregar (Abbot) on Jan 31, 2008 at 17:20 UTC
    Here's what I do in all my scripts (for example, from Krang):

    use File::Spec::Functions qw(catdir splitdir canonpath); use FindBin qw($RealBin); use Config; BEGIN { # Find a KRANG_ROOT based on path to bin my @dir = splitdir(canonpath($RealBin)); $ENV{KRANG_ROOT} ||= catdir(@dir[0 .. $#dir - 1]); # use $KRANG_ROOT/lib for modules my $lib = catdir($ENV{KRANG_ROOT}, "lib"); $ENV{PERL5LIB} = $ENV{PERL5LIB} ? "$ENV{PERL5LIB}:${lib}" : $lib; unshift @INC, $lib, "$lib/".$Config{archname}; }

    This uses the location of the script to find a "lib" dir in the parent directory. It then does the equivalent of a "use lib" as well as setting up PERL5LIB so that any sub-processes will use the same modules. You may not need the PERL5LIB setup if you aren't going to run any sub-processes that need to find Perl modules.

    This is better than putting a fully-qualified path in your script, in my opinion, because you can move your whole tree around and not change anything. This is particularly useful if you're working with other developers.

    -sam

      Modern perls don't need the Config{archname} stuff. The lib pragma does that automatically.
        Yeah, I think that's in there for v5.6.0 support on ancient Redhat releases. Probably time to dump it from my template.

        -sam

Re: lib pragma problem
by glide (Pilgrim) on Jan 31, 2008 at 18:08 UTC
    Hi,

    I normally use just this

    use FindBin; use lib "$FindBin::Bin/../../libs"; use module1; use module2;
    the bin from the FindBin give you the full path to you script.
      Thank you very much this was exactly what I was looking for.
      use FindBin; use lib "$FindBin::Bin/../../libs"; use module1; use module2;
Re: lib pragma problem
by citromatik (Curate) on Jan 31, 2008 at 17:22 UTC

    use lib 'mainfolder\modulesfolder'; is a relative path (relative to the path of your program). You should avoid that and specify a full path instead:

    use lib "/full/path/to/the/library";

    citromatik

Re: lib pragma problem
by friedo (Prior) on Jan 31, 2008 at 17:17 UTC
    Just use an absolute path to the module folder in the use lib line.