Perl – How to the Perl script find its module in the same directory

directorymoduleperl

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.

Best Solution

I am curious why the simplistic solution

use File::Basename;
use lib dirname (__FILE__);
use SomeModuleLocatedInTheSameDirectoryAsThisPerlScriptOrModule;

did not come up. The FindBin module seems to have some issues if the file is not the main executable perl script, but simply a non-executable Perl module. At least that's how I interpret the comment in the documentation. Did not really test it.

To have any other path relative to the location of this Perl file, do something like

use File::Basename;
use lib dirname (__FILE__) . "/MyModules";