How to locate perl modules in the same directory as the script

Perl of course allows you to identify the location of your perl modules by modifying @INC but is surprisingly rigid when it comes to placing module(s) in the same directory with the script.

This is fine for permanent installations or for scripts that depend on an installer but if you want to distribute a script plus module(s) for general use or just want flexibility to copy it from system to system without modifying the code the solution is relatively simple:

Setup: you write a perl module MyModule.pm that you’d like to include in the same directory as your script myScript.pl and allow the script to be called from anywhere.

in myScript.pl you would:


use MyModule.pm;

To contain your script and its supporting files in an arbitrarily located myScript directory you’d have to change into the myScript directory before executing myScript.pl:


$ mv myScript.pl myModule.pm /path/to/myScript
$ cd /path/to/myScript && ./myScript.pl

suppose you just want to execute it as


$ /path/to/myScript/myScript.pl

You’d get:


Can't locate MyModule.pm in @INC (@INC contains: /usr/lib..

Well the solution is fairly straightforward: parse the content of $0 to identify the location of myScript.pl (ostensibly MyModule.pm) and put it at the beginning of @INC:


BEGIN {
    my $script_dir = $0;
    if ($0 =~ /\/[^\/]+$/) {
        $script_dir =~ s/\/[^\/]+\/*\s*$//;
        unshift @INC, $script_dir;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *