For example, suppose you have your own directory under
/home/gilligan/lib, and you place your own
Navigation::SeatOfPants module in
/home/gilligan/lib/Navigation/SeatOfPants.pm.
Simply saying:
use Navigation::SeatOfPants;
is unlikely to do anything useful because only the system directories
(and typically the current directory) are considered for
@INC. However, even adding:
push @INC, "/home/gilligan/lib"; # broken
use Navigation::SeatOfPants;
doesn't work. Why? Because the
push happens at runtime, long after the
use was attempted at compile time. One way to fix
this is to add a BEGIN block around the
push:
BEGIN { push @INC, "/home/gilligan/lib"; }
use Navigation::SeatOfPants;
Because a use lib pragma will pretty much always
have a site-dependent pathname, it is traditional and encouraged to
put it near the top of the file. This makes it easier to find and
update when the file needs to move to a new system or when the
lib directory's name changes. (Of
course, you can eliminate use lib entirely if you
can install your modules in a standard @INC
locations, but that's not always practical.)
Think of use lib as not "use this
library," but rather "use this path
to find my libraries (and modules)." Too often, you
see code written like:
use lib "/home/gilligan/lib/Navigation/SeatOfPants.pm"; # WRONG
and then the programmer wonders why it didn't pull
in the definitions. Be aware that use
lib indeed runs at compile time, so this also
doesn't work:
my $LIB_DIR = "/home/gilligan/lib";
...
use lib $LIB_DIR; # BROKEN
use Navigation::SeatOfPants;