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

I spent some time with Super Search, looking for a way for a module to find its own location, but didn't have any luck. This is the best solution I could come up with:

MyModule.pm (self-locating module)
-----------
package MyModule; use strict; my $inc_dir; LOOP: foreach my $inc (@INC) { opendir(DIR, $inc) or next; while (my $module = readdir(DIR)) { if ($module eq 'MyModule.pm') { $inc_dir = $inc; closedir(DIR); last LOOP; } } closedir(DIR); } print "MyModule found at: $inc_dir\n"; 1;
mymodule.plx (test script)
------------
#!/usr/bin/perl -w # Test MyModule.pm use strict; use MyModule; print "Done.\n";
With this solution, there is a (IMHO small) chance for a race condition. Is there a better way to do this?

Impossible Robot

Replies are listed 'Best First'.
Re: Module Self-Location
by japhy (Canon) on Feb 08, 2002 at 16:28 UTC
    Embrace the %INC hash. $INC{"MyModule.pm"}

    _____________________________________________________
    Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
    s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

      Thanks, japhy! I spent a lot of time searching all over the place because I thought I had seen an easy way to do this. But I had forgotten that %INC was setting there holding just exactly the information I was looking for. :-)

      Update: Here's my updated self-locating module:
      package MyModule; use strict; my $inc_dir = $INC{'MyModule.pm'}; $inc_dir =~ s!/MyModule.pm$!!; print "MyModule found at: $inc_dir\n"; 1;
      Update 2: After a little more searching, I finally found the original node I was looking for: Read a static file from module directory.

      Impossible Robot
Re: Module Self-Location
by hakkr (Chaplain) on Feb 08, 2002 at 16:28 UTC
    The full path to a script is held in the special variable $0. Maybe there is one for a scripts modules ?
      Well, $0 only holds a relative path. For the full path, you should use FindBin's $Bin and $Script.

      _____________________________________________________
      Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
      s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;