Clinton
Clinton

Reputation: 23135

How can a perl module find its own path?

I'm creating my own module, lets call it X::Y. Of course, the module will be in the file X/Y.pm.

Lets say Y needs to call an external program, prog. Ideally I'd just like to put prog in X, so I can run X/prog. I'd like to not have hardcode X/progs full path, and for the module to work regardless of the current working directory set.

How can I find the full path of a module from inside a module? Or is there a better way to do this?

Upvotes: 7

Views: 3890

Answers (3)

plusplus
plusplus

Reputation: 2030

Borodin answered the question but some related information:

FindBin - finds the directory that the script was run from (use within the script itself or within a package loaded by it)

Neil Bower's CPAN modules for getting a module's path - detailed review of modules for finding another module's path.

Upvotes: 4

mob
mob

Reputation: 118591

Once a module is loaded, it's path is in the global %INC variable. To look it up, you need to do a simple conversion:

  1. change :: in the package name to /
  2. append .pm

So to find the location of the module X::Y, you would look in $INC{"X/Y.pm"}.

Upvotes: 0

Borodin
Borodin

Reputation: 126722

The full path to the source file currently being executed is supplied by Perl's __FILE__ special literal.

However I would prefer to see the external program installed where it would normally be, and the path there either coded as a constant in the Perl code or included in the PATH environment variable.

Upvotes: 10

Related Questions