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

Hi all I am writing a module function that needs to know its own directory location i.e. the directory location of the file containing the function. How to do this without searching @INC with a hardcoded file name?
  • Comment on Finding module directory from within module

Replies are listed 'Best First'.
Re: Finding module directory from within module
by merlyn (Sage) on Jul 30, 2009 at 05:59 UTC
    it's something like this.
    use File::Basename qw(dirname); use Cwd qw(abs_path); my $THIS_DIR; BEGIN { $THIS_DIR = dirname abs_path __FILE__; }

    -- Randal L. Schwartz, Perl hacker

    The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

      Thanks that works the way I wanted.
Re: Finding module directory from within module
by Anonymous Monk on Jul 30, 2009 at 06:56 UTC
    use Path::Class; my $THIS_DIR = file(__FILE__)->absolute->dir; print $THIS_DIR,"\n"; __END__

      ->absolute doesn't handle links, but Cwd's abs_path aka realpath does.

      use Cwd qw(abs_path); use Path::Class; my $THIS_DIR = file(abs_path(__FILE__))->dir; print $THIS_DIR,"\n";

      It's not very likely for module (.pm) files, but it's entirely possible for script (.pl) files.

        Interesting, but i'm not understanding how it makes a difference