SPUG: add a path to @INC

Andrew Sweger andrew at sweger.net
Sun Jan 16 18:53:42 PST 2005


On Sun, 16 Jan 2005, C.J.Collier wrote:

> Note that if you want to use C<@INC> to C<use()> modules, I believe you 
> need to put the C<use lib '...';> in a C<BEGIN { ... }> block, thus:

PODcity!

I think you're wrong. But I'll have to write a test now to double-check
myself...

File: ./ascript.pl
--------------------------------------------------------------
#!/usr/lib/perl

use warnings;
use strict;
use lib './mylib';
BEGIN {
    print "About to load Ned...\n";
    use Ned;
    print "Done loading Ned.\n";
}

my $foo = new Ned;
$foo->hello;
--------------------------------------------------------------

File: ./mylib/Ned.pm
--------------------------------------------------------------
package Ned;
use warnings;
use strict;

sub new {
    my $foo = {};
    return bless $foo; # Hey! I wouldn't do this for real.
}

sub hello {
    my $thing = shift;
    print "Hello\n";
}

print "Done loading module Ned. Thank you. Come again.\n";
return 1;
--------------------------------------------------------------

% perl ./ascript.pl
Done loading module Ned. Thank you. Come again.
About to load Ned...
Done loading Ned.
Hello
%

Note that all of the 'use' clauses are parsed and loaded even the one
*inside* the BEGIN block. Thus, there's no point putting bare use clauses
inside BEGIN blocks. Usually one uses a require in a BEGIN block (in a
module) to conditionally load a module (as the lib pragma does to load
File::Spec on MacOS). As long as the lib pragma falls before the 'use'
"call" loading your module in a directory located via the lib pragma, it
should work.

> I could be wrong, though.  Whee.

See? It happens to the best people too. Not just me.

-- 
Andrew B. Sweger -- The great thing about multitasking is that several
                                things can go wrong at once.



More information about the spug-list mailing list