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 that you’d like to include in the same directory as your script and allow the script to be called from anywhere.

in you would:


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

$ mv /path/to/myScript
$ cd /path/to/myScript && ./

suppose you just want to execute it as

$ /path/to/myScript/

You’d get:

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

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

    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 *