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;
    }
}
This entry was posted in Perl, Programming on by .

About morgan

Morgan is a freelance IT consultant living in Philadelphia. He lives with his girlfriend in an old house in Fishtown that they may never finish renovating. His focus is enterprise Messaging (think email) and Directory. Many of his customers are education, school districts and Universities. He also gets involved with most aspects of enterprise Linux and UNIX (mostly Solaris) administration, Perl, hopefully Ruby, PHP, some Java and C programming. He holds a romantic attachment to software development though he spends most of his time making software work rather than making software. He rides motorcycles both on and off the track, reads literature with vague thoughts of giving up IT to teach English literature.

Leave a Reply

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