Search code examples
perlmoduledirectory

How can my Perl script find its module in the same directory?


I recently wrote a new Perl script to kill processes based on either process name / user name and extended it using Classes so that I could reuse the process code in other programs. My current layout is -

/home/mutew/src/prod/pskill       <-- Perl script
/home/mutew/src/prod/Process.pm   <-- Package to handle process descriptions

I added ~/src/prod in my $PATH variable to access the script from anywhere. On running the script from any directory other than its resident directory leads to a "Can't locate Process.pm in @INC" (which is understandable given that other than the shared directories in /usr, @INC includes only the current directory - '.'). One workaround that I have been using is the use lib directive as so -

use lib '/home/mutew/src/prod';

but this is a major portability issue. Any solutions which will also allow me to export the script to other systems without and changes?


EDIT

  1. I chose 'depesz' answer as the correct one because of its simplicity and core module usage.
  2. brian d foy's answer though suggests other methods to accomplish the same (TMTOWTDI), his contribution in perlfaq8 renders this question absolutely redundant.

Solution

  • The simplest approach I found it to use FindBin module. Like this:

    use FindBin;
    use lib $FindBin::Bin;
    

    Generally I prefer to have my scripts provided in such a way that programs are in whatever/bin, and libraries are in whatever/lib

    In these situations I use a slightly more complicated approach:

    use Cwd qw(abs_path);
    use FindBin;
    use lib abs_path("$FindBin::Bin/../lib");
    

    The abs_path call is to make the @INC contain whatever/lib, and not whatever/bin/../lib - it's just a slight change, but makes reading error messages easier.