perlpathincludeperl-module

How does a Perl program know where to find the file containing Perl module it uses?


If my Perl program uses Perl modules, how will it determine where to find the file containing the module code?

For example, if the program contains:

use MyModule1;              # Example 1
use This::Here::MyModule2;  # Example 2

where will it look?


Solution

  • Perl interpreter (which runs your perl program) will use a special array called @INC to search for a file containing the module.

    Each value in the @INC array is a directory name (but see note below); Perl will search within those directories in a loop using the rules specified below. (Please refer to this SO post for details of how the contents of @INC are determined).

    If the module's file is not found after exhausting @INC, the program's compilation will be aborted with an error. If the module's file is found in one of the directories specified in @INC, the search is finished without looking at the rest of @INC.

    The way Perl searches for a module file within each of the directories listed in @INC is as follows:

    Let's go over a specific example, assuming that your @INC contains two sub-directories: ("/usr/lib/perl", "/opt/custom/lib").

    Then Perl would search as follows:

    ==========================================================================
    | Module                | Try # | File to try               
    ==========================================================================
    | MyModule1             | Try 1 | /usr/lib/perl/MyModule1.pm
    | MyModule1             | Try 2 | /opt/custom/lib/MyModule1.pm
    ==========================================================================
    | This::Here::MyModule2 | Try 1 | /usr/lib/perl/This/Here/MyModule2.pm
    | This::Here::MyModule2 | Try 2 | /opt/custom/lib/This/Here/MyModule2.pm
    ==========================================================================
    

    Please recall that Perl interpreter will STOP trying to search once it finds the file in one of the locations, without trying to see if the file is in later locations as well. E.g. if /usr/lib/perl/This/Here/MyModule2.pm exists, then Perl will not look for, nor care about the existence, of /opt/custom/lib/This/Here/MyModule2.pm.

    NOTE: @INC is used whenever Perl interpreter is using require-like mechanism for importing Perl modules. This includes: