in reply to Re^2: Perl Script own path
in thread Perl Script own path
So,
to get name of program: File::Basename::basename($0);
to get absolute path: Cwd::abs_path($0); NOT Cwd::Cwd()
To be portable, you must use abs_path() before doing anything that changes the current working directory, eg chdir().
I tested on Windows XP and Fedora Linux.
$0 on Windows was the full absolute path of the executing script, but with Windows style "\" instead of "/".
$0 on Linux was essentially what was typed into the shell to run the script. Something like this: "../test/whereami.pl" gave exactly that for $0.
When using Cwd::abs_path($0), on Windows the backslashes ('\') were converted to forward slashes ('/') - the full path stayed the same since $0 was the full path to begin with. A chdir() on Windows had no effect upon the result of abs_path().
On Linux, abs_path does some text massaging of rel2abs()'s output which itself a result of using Cwd::cwd() so if working directory is changed, abs_path() will be wrong. (oh, abs_path() probably doesn't call rel2abs() but it looks like it does whatever rel2abs() does. Oh, the rel2abs() function in File::Spec... in my Unix test case it concatenates $0 onto what cwd() says. So in my test case, >cd b >../test/whereami.pl, you get a path like: blah../marsh/b/..test/whereami.pl. This is a valid path, but the detour through unrelated directory b is not needed. abs_path() evidently takes this path and eliminates the trip through dir b.
This is also one of those cases where "use English;" just serves to further confuse the reader because:
$program_name = File::Basename::basename($PROGRAM_NAME); because of course $0 is NOT the program's name. I don't think there is a good "english name" for $0 because "its sometimes this and sometimes that" is hard to express in one short name!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Perl Script own path
by Anonymous Monk on Jul 27, 2011 at 07:57 UTC | |
by Marshall (Canon) on Jul 27, 2011 at 08:20 UTC |