Using local::lib

by Scott, Revised on September 22, 2011 (Perl)

local::lib is used to install Perl modules to a user's home directory without root privileges. These modules are then used rather than the installed system modules while using the system build of the Perl interpreter along with any system modules that are not a part of the local install.

Two reasons to use:

  1. It gives the ability to install perl modules within the user's directory without root access.
  2. Even if you have root access, you can install the most recent versions of modules to a user directory without overwriting the system versions (which are maintained by the package manager).

Go to CPAN and download the latest version. Unpack the archive and cd into the directory.

tar -zxf local-lib-1.004006.tar.gz
cd local-lib-1.004006

Tell local::lib to "bootstrap" itself. This creates a "perl5" folder within the home directory, and instructs the toolchain to install local::lib there.

perl Makefile.PL --bootstrap=~/perl5

When asked if CPAN.pm should be configured automatically, just press Enter to accept the default value ("yes").

When the configuration has finished, enter the following commands which will build, test, and install local::lib.

make && make test && make install

To automatically enable (use of user installed modules) within a terminal, place the following in the ~.bashrc file:

echo 'eval $(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)' >>~/.bashrc

Or run the from a terminal command line:

eval $(perl -I$HOME/perl5/lib/perl5 -Mlocal::lib)

(Information credit for the above information: Jon Allen.)

Why not in .bashrc? Because I still want to use the system installed modules for a project that is based on the system installed modules.

The last step is to configure CPAN.

From day 3 of the 2009 Perl Advent Calendar comes the tip to place this code at the top of a script:

use local::lib('~/perl5');

However, it does not work unless local::lib can be found initially (if local::lib is under ~/perl5, then this command won't work). The following command before the above would work:

use lib('/home/user/perl5/lib/perl5');

Apparently, "lib" does not recognize the "~" shortcut for the "home" directory. The above works, but now it is getting cumbersome. I found building the local::lib module using dh-make-perl puts it in the system perl's lib location and will now work without the "use lib."

dh-make-perl --build --cpan local::lib

However, this needs root access and may defeat one of the reasons for using local::lib in the first place.

I also had a need to add to the PERL5LIB variable without wiping out the PERL5LIB set by my local::lib.  The following export worked for me (command line or in ~.bashrc):

export PERL5LIB=${PERL5LIB}:/path/to/perl/libs

Tags: Perl