Perl – use lib is relative to $PWD

When you do a ‘use lib’ with a relative directory what is it relative to? The current working directory? The script? Something in @INC?

<p>Let’s test:</p>
<p><code>> mkdir inctest<br />

cd inctest
mkdir bin
mkdir lib
cat > lib/IncTest.pm
package IncTest;

<p>1;</p>
<p>> cat > bin/test.pl<br />

!/usr/bin/perl -w

<p>use lib ‘../lib’;<br />

use IncTest;

<p>> cd bin<br />

perl ./test.pl
cd ..
perl bin/test.pl
Can’t locate IncTest.pm in @INC (@INC contains: ….)

<p>because . in ‘use lib’ is relative to the execution, not the script.</p>
<p>“But I want to distribute code and modules together and have the script find its modules!” you cry.  Enter the standard FindBin module.</p>
<p><code><br />

cd inctest
cat > bin/test.pl

!/usr/bin/perl -w

<p>use FindBin;<br />

use lib “$FindBin::Bin/../lib”;

<p>use IncTest;</p>
<p>> cd bin<br />

perl ./test.pl
cd ..
perl bin/test.pl

<p>So we’ve demonstrated that perl’s ‘use lib’ is relative to the $PWD of the user and if this isn’t the desired effect it can be avoided using <a href="http://search.cpan.org/~nwclark/perl-5.8.7/lib/FindBin.pm">FindBin</a>.  mod_perl users will want FindBin::Real which works in a re-used interpreter environment.