Haiyuan Zhang
Haiyuan Zhang

Reputation: 42822

What's the search order in perl's include path when a module is loaded

Let's say there are three paths in @INC: path1, path2 and path3. Under each of these paths, there is a module named foo.pm. If I now load foo.pm in my script via use foo;, which of the foo.pms is actually going to be loaded? Or in other words, what is perl's search order for paths in @INC?

Upvotes: 5

Views: 3738

Answers (2)

Axeman
Axeman

Reputation: 29854

path1, path2, path3. And perl will load path1/foo.pm.

Why would you expect it to be any other?

Looking at perlfunc perlvar, I can see that they don't explicitly say this, but they do say:

The array @INC contains the list of places that the do EXPR , require, or use constructs look for their library files.

I think the hint on there is list. It's unexceptional to expect a list to be processed first-to-last.

You could probably put this code, right before your use foo; statement:

BEGIN { say "\@INC=(${\join( ', ', @INC )})"; }

If that still shows you @INC=(/path1, /path2, /path3) then put this after the use statement:

BEGIN { say "\$INC{'foo.pm'}=$INC{'foo.pm'}"; }

And if that one still shows $INC{'foo.pm'}=/path3/foo.pm, then I think you're not specifying your search paths as well as you might. You might think you have foo.pm in the same directory specified as '/path1', but the likelihood is that you've got some path messed up.

Upvotes: 6

toolic
toolic

Reputation: 62105

perldoc -v %INC shows which path was chosen:

use Data::Dumper; 
print Dumper(\%INC);

Or...

perl -Mfoo -e 'print $INC{"foo.pm"}'

require shows some psuedo-code which implies the search order:

foreach $prefix (@INC) {
}

Thus, path1 would be searched first.

Upvotes: 8

Related Questions