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

Hi,

I was looking up previous posts on how to get the path to a script. It seems the preferred suggestion is

use Cwd qw(abs_path); my $path = abs_path($0);
However, when I do this, I get the path including the script file itself, e.g. if I run a script /long/path/to/some/script.plx, abs_path($0) returns the whole thing and not /long/path/to/some/ as I expected. So I still have to use a regex to remove the script name, but someone in the old posts said that was looking for trouble.

Is that, uh, intended/normal, or am I doing something wrong?

And as long as I'm at it: Basically, I want to ensure that relative paths containing information the script needs are always correct, even if I call the script from somewhere else by specifying the path, like maybe

.../other/dir/ $ ../../some/script.plx
So I wanted to get the path and then chdir there. Is that the right way to go about it or is there a much easier way? I tend to think too complicated sometimes :-/ I'm on Linux and portability isn't an issue.

Replies are listed 'Best First'.
Re: Difference btw. abs_path and $0?
by toolic (Bishop) on May 25, 2012 at 18:07 UTC
    You could also use File::Basename
    use Cwd qw(abs_path); use File::Basename; my $dir = dirname(abs_path($0)); print "$dir\n";
Re: Difference btw. abs_path and $0?
by tinita (Parson) on May 25, 2012 at 20:26 UTC
Re: Difference btw. abs_path and $0?
by Your Mother (Archbishop) on May 26, 2012 at 02:49 UTC

    This is how I like to do that kind of thing–

    use strictures; use Path::Class "file"; use File::Spec; my $script = file( File::Spec->rel2abs(__FILE__) ); print $script, $/; printf("HURR -> %s\nDERR -> %s\nDERP -> %s\n", $script->basename, $script->parent, $script->as_foreign("Win32"), ); __END__ /Users/moo/depot/tmp/pm-972505.pl HURR -> pm-972505.pl DERR -> /Users/moo/depot/tmp DERP -> \Users\moo\depot\tmp\pm-972505.pl

    You can chain ->parent and use the methods like relative to do lots of easy to follow path handling code; Path::Class::File, Path::Class::Dir. Sidenote: cd'ing around in scripts, to me, has a pretty strong code smell and whenever I see it in the wild it seems to come with too many assumptions and too little error checking.

Re: Difference btw. abs_path and $0?
by Anonymous Monk on May 26, 2012 at 08:06 UTC

    returns the whole thing and not /long/path/to/some/ as I expected

    If you read Cwd you can learn why you expect the wrong thing