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

Hi, I'm trying to use a file that is located in a different directory up from the actual Perl script file. I'm unable to get this to work, however.... Using use myfile; fails with Can't locate..., and adding ../ to 'help' Perl locate the file, results in syntax error at.....

Is there anyway to include a file (.pm file) that is in a different directory then the actual script file? (Out side of copying the file into the same directory (result: redundant code) or installing to the Perl directory (no access)).

Replies are listed 'Best First'.
Re: using a file in a different dir
by shemp (Deacon) on Nov 01, 2005 at 08:31 UTC
    use lib is what you need. It is used to add directories to the @INC array, which is a list of the directories to look for files that are require'd or use'd. So above your use myfile statement, add a use lib directory staetment to include the directory that myfile is in.
    #!/usr/bin/perl use strict; use warnings; use lib '/home/someuser/somedir'; use myfile;
    Just put in the absolute directory path where i have the directory specified. I know that there is something odd about using '..' in an @INC path, but i cant remember exactly what, someone else should know.

    I use the most powerful debugger available: print!
Re: using a file in a different dir
by pajout (Curate) on Nov 01, 2005 at 08:31 UTC
    If you wish to use some module located in your proprietary directory, do something like as
    use lib "/usr/local/me/my_dir"; use MyModule;
    It supposes file /usr/local/me/my_dir/MyModule.pm
Re: using a file in a different dir
by Corion (Patriarch) on Nov 01, 2005 at 08:33 UTC

    The use statement searches a module in @INC. The lib pragma adds directories to @INC. So you will likely want to tell Perl (for this script) to also look elsewhere for your code:

    use lib '../foo';

    If you have a directory with modules that you always want to use, you can set $ENV{PERL5LIB} (or was it $ENV{PERL5INC} ?). If you only want to alter the module search path for one invocation of your program, you can invoke it as:

    perl -I../foo my_script.pl

      Saying use lib "../lib"; works fine if you're always going to run the script from the directory in which it's located. If you run it from somewhere else, however, this will break.

      It's better is to use the FindBin module in conjunction with use lib. For example, you could say:-

      use FindBin '$Bin'; use lib "$Bin/../lib";
      Which will add the directory "../lib" relative to where the script is installed (instead of relative to your current directory) to @INC.

Re: using a file in a different dir
by Delusional (Beadle) on Nov 01, 2005 at 09:05 UTC
    Thanks all. With your help, it now works.