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

I'm sure there's an obvious answer to this, but I can't seem to find it. Suppose I have these files:
/(lib path)/dirAAA/ModuleA.pm /(lib path)/dirBBB/ModuleB.pm
where (lib path) will differ from one installation to another. Also for various reasons I can't put ModuleA and ModuleB in the same directory. ModuleA needs to use ModuleB. In ModuleA I put:
use lib ???; use ModuleB;
What do I use for ??? I know that these are no good: # WRONG: relative to caller who could be anywhere:
<code> use lib '../dirAAA/'
# WRONG: relative to calling script which could be anywhere:
use FindBin; use lib "$FindBin::Bin/../dirAAA/"
How do I specify 'relative to the current file (Module A)'? My apologies for posting anonymously; I'm having trouble logging in. thanks, David

Replies are listed 'Best First'.
Re: use lib between modules
by dragonchild (Archbishop) on Feb 14, 2005 at 19:07 UTC
    Presumably, you've done a use lib qw( /(lib path)/dirAAA ); somewhere prior to running the code in ModuleA, otherwise you wouldn't have gotten there.

    One, somewhat hackish, solution is to inspect @INC.

    BEGIN { my $lib_to_use; foreach my $dir (@INC) { $lib_to_use = $dir, last if $dir =~ m!dirAAA/?$!; }; $lib_to_use =~ s!dirAAA!dirBBB!; use lib $lib_to_use; } use ModuleB;

    I'm sure there's a module that does this, but I'm too lazy to look for it.

    Being right, does not endow the right to be rude; politeness costs nothing.
    Being unknowing, is not the same as being stupid.
    Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence.
    Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.

      Thanks dragonchild and Tanktalus.
      First, I'm relieved that I wasn't overlooking something obvious. Second, I'm surprised that there isn't a more straightforward way of doing this. But maybe that's not a bad thing. As you both pointed out, it's probably better if all the application specific modules reside in the same directory, if possible. Thanks again!
      -David
Re: use lib between modules
by Tanktalus (Canon) on Feb 14, 2005 at 19:07 UTC

    In my ideal world, I'd have /(lib path) in the lib already, and then use dirAAA::ModuleA and dirBBB::ModuleB.

    Assuming, however, that you're really using "use ModuleA" to get at ModuleA, you can use %INC:

    my $libpath; BEGIN { ($libpath = $INC{'ModuleA.pm'}) =~ s:/dirAAA/.*:dirBBB:; } use lib $libpath;