use blib

ferreira on 2007-08-03T19:25:35

I was reading the code of "blib.pm" and thinking why it is written that way. Why using "Cwd" when relative paths work perfectly?

The implementation of "blib" does something similar to this:

sub import {
    my $blib = abs_path('blib/lib');
    push @INC, $blib;
}


(Well, it is much more complicated, but that's what matter to the discussion here.) This can be compared to just:

use lib qw(blib/lib);


The gotcha is that resolving the relative directory into an absolute path is insensitive to further changes in the current directory. The former simple solution would fail in such cases.

For example, you are testing a "Foo" distribution package. You enter the uncompressed package directory, does "perl Makefile.PL; make" and prepares to run a test script, like that one:

# t/foo.t
use Test::More tests => 1;

diag("INC: @INC"); BEGIN { chdir "t" } require_ok('Foo');


If you use "blib", you will be happy.

$ pwd
/home/me/Foo

$ perl -Mblib t/foo.t 1..1 # INC: /home/me/Foo/blib/arch /home/me/Foo/blib/lib ... ok 1 - require Foo;


If you prefer "lib qw(blib/lib)", kaboom.

$ perl -Mlib=blib/lib t/foo.t
1..1
# INC: blib/lib ...
not ok 1 - require Foo;
#   Failed test 'require Foo;'
#   at t/foo.t line 8.
#     Tried to require 'Foo'.
#     Error:  Can't locate Foo.pm in @INC (@INC contains: blib/lib ...) at (eval 3) line 2.
# Looks like you failed 1 test of 1.


Ok, just taking notes while I try to become smarter.


blib looks up, too

brian_d_foy on 2007-08-04T17:42:19

blib does more than just add blib/lib to your @INC. If it doesn't find the module there it starts working its way back in the directory structure looking for a blib/blib that does contain the module.

blib does more

ferreira on 2007-08-05T16:23:30

Yep, I know that blib tries hard to be handy. It also adds the architecture-dependent directories and does the right thing if used with arguments which end with '/' or 'blib'. I only stuffed this into the comment "it is much more complicated" to concentrate on the "WTF Cwd is doing there".