in reply to Finding module directory from within module

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

Replies are listed 'Best First'.
Re^2: Finding module directory from within module
by ikegami (Patriarch) on Jul 30, 2009 at 07:27 UTC

    ->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

        Example:

        $ mkdir foo $ cat > foo/Module.pm package Module; use Cwd qw( realpath ); use Path::Class qw( file ); print( "absolute: ", file(__FILE__)->absolute->dir, "\n"); print( "realpath: ", file(realpath(__FILE__))->dir, "\n"); 1; $ perl -Mlib=foo -e'use Module' absolute: /tmp/ikegami/foo realpath: /tmp/ikegami/foo $ ln -s foo bar $ perl -Mlib=bar -e'use Module' absolute: /tmp/ikegami/bar realpath: /tmp/ikegami/foo $ mkdir baz $ ln -s ../foo/Module.pm baz/Module.pm $ perl -Mlib=baz -e'use Module' absolute: /tmp/ikegami/baz realpath: /tmp/ikegami/foo