Main Content

Changing @INC - where Perl loads its modules

Archive - Originally posted on "The Horse's Mouth" - 2006-02-02 05:41:41 - Graham Ellis

Where does Perl load modules from in its use and require statements? It loads them from directorys in a special list called @INC, from files with a .pm extension in those directorys.

When Perl's installed, @INC is set to a list of directorys that includes generic locations for its standard modules, some release specific directories, and "." the current directory, which are checked in order each time you do a use or require.

Some ways to modify @INC

** You can add to the list in @INC by using the -I command line option:
perl -I /Users/grahamellis/jan06 i2
says "run the perl program i2, additionally checking the jan06 directory for modules"

** You can add to the list within your program by doing so in a BEGIN block prior to the use statements:
BEGIN {
push @INC,"/Users/grahamellis/jan06";
}
use demo;
print "hello world";

Rather curiously, use calls are run at compile time not at run time ... but then so are BEGIN blocks ... so you put your manipulation of @INC into one of those to get it to happen early enough.

** You can add to the beginning of the list by setting the PERL5LIB environment variable prior to running your program:
export PERL5LIB=/Users/grahamellis/jan06
and you can use a colon separated list for that if you want to pre-pend more than one directory.


Footnote - don't you just love Perl's "There's more than one way to do it". Thanks to Dave Cross - author of various Perl books - for reminding me of use lib; - see the comments he's added for a description of this in his own words