Thursday, March 3, 2011

Add or modify module paths (@INC) in Perl

Here are additional ways to add or modify module paths (@INC) in Perl beyond the BEGIN blocks and basic use lib shown in your selection:

1. Using the -I Command-Line Switch
You can add a directory to @INC at runtime without modifying the script's code. This is useful for testing or one-off executions.

Bash
perl -I/my/custom/path script.pl

2. Using the PERL5LIB Environment Variable
If you want a specific module path to be available to all Perl scripts run in your current terminal session or environment, you can export PERL5LIB. Perl automatically checks this variable and prepends its contents to @INC.

Bash
export PERL5LIB=/my/custom/path
perl script.pl

3. Adding Paths Relative to the Script (Using FindBin)
When building projects, hardcoding absolute paths like c:/cgywin/ is brittle. A better approach is to use standard modules like FindBin to dynamically add a lib directory located relative to where your script is saved.

Perl
use FindBin;                  # Locates the full path to the script's directory
use lib "$FindBin::Bin/lib";  # Adds the 'lib' folder inside the script's directory to @INC

# You can also go up a directory level
use lib "$FindBin::Bin/../lib"; 

4. Adding Multiple Paths with use lib
The use lib pragma can accept a list of directories, allowing you to include multiple custom paths in a single, clean statement.
Perl
use lib ('/first/custom/path', '/second/custom/path');

--------------------------------------------------

BEGIN { push @INC, 'd:/purand/' }

# or

BEGIN { unshift @INC, 'e:/purand/temp' }

# or

use lib 'c:/cgywin/';
print "@INC";

No comments: