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

P

PerlFAQ Server

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
program:

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
perlfaq.pod.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top