FAQ 8.48 How do I add the directory my program lives in to the module/library search path?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

This is an excerpt from the latest version perlfaq8.pod, which
comes with the standard Perl distribution. These postings aim to
reduce the number of repeated questions as well as allow the community
to review and update the answers. The latest version of the complete
perlfaq is at http://faq.perl.org .


8.48: How do I add the directory my program lives in to the module/library
search path?

    (contributed by brian d foy)

    If you know the directory already, you can add it to @INC as you would
    for any other directory. You might <use lib> if you know the directory
    at compile time:

            use lib $directory;

    The trick in this task is to find the directory. Before your script does
    anything else (such as a "chdir"), you can get the current working
    directory with the "Cwd" module, which comes with Perl:

            BEGIN {
                    use Cwd;
                    our $directory = cwd;

            use lib $directory;

    You can do a similar thing with the value of $0, which holds the script
    name. That might hold a relative path, but "rel2abs" can turn it into an
    absolute path. Once you have the

            BEGIN {
                    use File::Spec::Functions qw(rel2abs);
                    use File::Basename qw(dirname);

                    my $path   = rel2abs( $0 );
                    our $directory = dirname( $path );

            use lib $directory;

    The "FindBin" module, which comes with Perl, might work. It finds the
    directory of the currently running script and puts it in $Bin, which you
    can then use to construct the right library path:

            use FindBin qw($Bin);

    You can also use "local::lib" to do much of the same thing. Install
    modules using "local::lib"'s settings then use the module in your

             use local::lib; # sets up a local lib at ~/perl5

    See the "local::lib" documentation for more details.


The perlfaq-workers, a group of volunteers, maintain the perlfaq. They
are not necessarily experts in every domain where Perl might show up,
so please include as much information as possible and relevant in any
corrections. The perlfaq-workers also don't have access to every
operating system or platform, so please include relevant details for
corrections to examples that do not work on particular platforms.
Working code is greatly appreciated.

If you'd like to help maintain the perlfaq, see the details in

Site Timeline