Chapter 4. Working with ModulesHacks 28-42
Perhaps the greatest invention of Perl 5 is the idea of modules. They allow people to modify the language and reuse code far beyond what Larry and the Perl 5 porters ever
If you're doing any serious work with Perl, you'll
Here are several ideas that show off the varied ways that you can extend your programs. CPAN is only an arm's length away. Be ready. |
Hack 28. Shorten Long Class
|
Hack 29. Manage Module Paths
Keep your code where it makes sense to you, not just to Perl.
Perl's a flexible language and it
Whatever the case, Perl gives you options to manage where it looks for modules. Suppose you have a program in your
~/work
directory that uses a module named
Site::
Within Your Program
The simplest and most self-contained way to change Perl's search
use lib 'lib'; use Site::User; adds the lib/ directoryrelative to the current directoryto the front of Perl's search path list. Similarly: no lib 'badlib'; use Site::User;
From the Command Line
Sometimes you don't have the option or the
$ perl -Mlib=lib show_users.pl This is equivalent to use lib 'lib' . To exclude a path, prepend a hyphen to lib : $ perl -M-lib=badlib show_users.pl
With an Environment Variable
Of course, modifying every program or remembering to add a command-line switch to every invocation is a tremendous hassle. Fortunately, there's a third option: set the
PERL5LIB
environment variable to a
$ export PERL5LIB=/home/user/work/lib:/home/user/work_test/lib:$PERL5LIB % setenv PERL5LIB /home/user/work/lib:/home/user/work_test/lib:$PERL5LIB There's no good and easy way to exclude a directory for the search path here; put the correct directory at the front of the path.
If you put the appropriate invocation in the appropriate startup file (such as
/etc/profile
or the equivalent), users do not even have to know that this path is there. Of course, if they run programs from
cron
or another environment without these
An easier option may be to write a simple shell script that sets the environment properly and then launches the actual perl binary, passing along the command-line options appropriately. When Recompiling PerlYour final recourse is to set the appropriate paths when compiling Perl [Hack #67]. This isn't as bad as it sounds, but it does take a little bit more dedication. Once you have downloaded and unpacked Perl, run the Configure script. Answer all of the questions appropriately until it asks: Enter a colon-separated set of extra paths to include in perl's @INC search path, or enter 'none' for no extra paths. Colon-separated list of additional directories for perl to search? [none]
Type there the list of directories to add to Perl's built-in
@INC
. Note that
perl
will search this directory
after
it searches its core directories, so if you want to load something in place of a
|