cvg2mco has asked for the wisdom of the Perl Monks concerning the following question:

Is it possible to include a library path when a certain module::function is called? I understand we could do this for the module as use autouse 'Module' => qw (function1, function2) But I am not sure if the same can be done to specify the path. Any help in this regard is appreciated. Some info: We have a shell script that executes this perl script in the background. Also this shell script is executed during system startup. And the module path (dir where the module lives) is created at system startup after this shell script (daemon) is started. So if i could include the module at a later time then the perl script would not error out.

Replies are listed 'Best First'.
Re: use lib and use autouse 'module'
by Hue-Bond (Priest) on Jul 28, 2006 at 23:16 UTC

    You can always unshift directories into @INC whenever you want. What you haven't specified is how are you going to let the program know what directory it should unshift. Once you get it into the program, it's easy:

    ## File: FOO.pm package FOO; print "loading foo\n"; sub foo { print "in foo::foo\n"; } 1;
    ## main program use autouse 'FOO' => qw/foo/; unshift @INC, '.'; foo; __END__ loading foo in foo::foo

    --
    David Serrano

      Thanks for your quick response. I have information on the directory that this module will reside. The perl script is designed as a file watcher and the process files with the functions from the module. In the loop (for file watcher) i look to see if the common mount point exists and if it does then I call the modules function to process the file. so if I understand you correct, I could do
      ## PERL SCRIPT ## #!/usr/bin/perl; use strict; my $g_commonMount = "/common_mount"; my $g_moduleDir = "$g_commonMount/include"; sub fileWatcher { while(1) { if ( -d $g_moduleDir ) { use autouse 'foo' => qw/foo/; #using your example unshift @INC, '$g_moduleDir'; #foo.pm is under $g_moduleDir foo; } sleep (10); } } #### MAIN ### &fileWatcher; __END__

        Ah, the directory is known from the beginning. That makes things easier. There's no need to unshift anything, since you can use lib(*).

        #!/usr/bin/perl ## untested use warnings; use strict; my ($g_commonMount, $g_moduleDir); BEGIN { $g_commonMount = "/common_mount"; $g_moduleDir = "$g_commonMount/include"; } use lib $g_moduleDir; sub file_watcher { while (1) { sleep 10, next unless -d $g_moduleDir; use autouse 'foo' => qw/foo/; foo; } } file_watcher;

        I'm not particularly proud of the BEGIN block but maybe there's another way to do it. Also, instead of autouse(*), you can use require.

        (*) CPAN seems down now, so the links to the modules may be wrong, since they are core and I don't know if one can link to them in the same fashion as any other.

        --
        David Serrano