הלינקייה: מגזין חודשי למפתחים

רוצה לשמוע על כל האירועים, המדריכים, הקורסים והמאמרים שנכתבו החודש ?
הלינקייה הינו מגזין חופשי בעברית שמשאיר אותך בעניינים.
בלי ספאם. בלי שטויות. פעם בחודש אצלך בתיבה.

Modules Search Paths

When running a perl program that uses modules, perl needs to find its dependencies. Perl search paths define where perl looks for its modules. The list of paths perl uses to find modules is stored in a global array called @INC.
The easiest way to view its current value is use perl -V. The relevant part is the last block which looks like this:

  @INC:
    /Users/ynonperek/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3/darwin-2level
    /Users/ynonperek/perl5/perlbrew/perls/perl-5.16.3/lib/site_perl/5.16.3
    /Users/ynonperek/perl5/perlbrew/perls/perl-5.16.3/lib/5.16.3/darwin-2level
    /Users/ynonperek/perl5/perlbrew/perls/perl-5.16.3/lib/5.16.3
    .

In the above example, the default search path includes the 4 directories in the list, and the current running directory. Now let's see how we can add more directories to the search path list.

1. Add to @INC

@INC is just a normal array in perl, so we can simply add to it using something like:

# WARN Don't Use This as is

unshift @INC, '/my/modules/folder';

But this won't work, since "use" calls happen at compile time, while unshift happens at run time. We can move the unshift to compile time using a BEGIN block, like this:

BEGIN {
  unshift @INC, '/my/modules/folder';
}

Or use the nicer looking (but equivalent) - use lib:

use lib '/my/modules/folder';

The lib pragma takes a folder as argument and adds it to @INC. Since use statements happen at compile time, all you need to do is place use lib above all other use statements.

2. Use PERL5LIB

When working in a team, it's nice that we can share our modules with everyone else in the team without specifying the shared module path in every script. It's also easier for new users to join in and write scripts without worrying where all the dependencies are.

The environment variable PERL5LIB can hold a list of paths, and it will be appended automatically to @INC at startup. try the following from your UNIX shell:


# CSH users
setenv PERL5LIB /my/modules

# Bash users should use
# export PERL5LIB=/my/modules

# Now print @INC
perl -V

You should see @INC now includes /my/modules.

By setting PERL5LIB in the shell's rc file, you can make sure all of the developers in your team share the same modules.

course: