views:

61

answers:

2

In C / C++ (bash, too?) the first command-line argument, argv[0], is the binary filename (prefixed by an absolute or relative path as invoked by the user).

In Perl the first command-line argument $ARGV[0] is the first command-line argument after the path and name of the script.

How can a Perl script get the path and name that was used to invoke it?

Thanks!

+4  A: 

$0 contains the name of the file containing the perl script being executed.

Bertrand Marron
+4  A: 

"In C / C++ (bash, too?) the first command-line argument, argv[0], is the binary filename"

is dead wrong, by the way. The ISO standard mandates no such thing.

From C99:

If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment.

And notice that it states "represents the program name", not "is the location of the binary executable". That's because there's an earlier snippet which states:

... the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup."

It's quite legal for your argv[0] for the command "sleep 60" to be "pax's fantastic sleep utility" rather than "/bin/sleep".

In short, the environment doesn't have to provide a representation of the program and, even if it does, it doesn't have to be anything usable for locating the binary.


But, having bored you with my diatribe, Perl provides $0 or $PROGRAM_NAME (in that hideous "English" mode) for this purpose. See perlvar for details.

paxdiablo
Ok, fine. I guess I wasn't looking for perfect portability. BTW, does POSIX say anything about what argv[0] contains?
Posco Grubb
I shouldn't have associated this argv behavior with C or any high-level language. Here is what POSIX.1 says:http://www.opengroup.org/onlinepubs/009695399/functions/exec.htmlThe argument argv is an array of character pointers to null-terminated strings. The application shall ensure that the last member of this array is a null pointer. These strings shall constitute the argument list available to the new process image. The value in argv[0] should point to a filename that is associated with the process being started by one of the exec functions.
Posco Grubb
No probs, Posco, I just thought I'd bring it up. When someone talks about the C standard, it invariably means ISO - POSIX is the next level up, so to speak. In any case, once you get used to the "language lawyers" that put together standards documents (and our requirements docs), you realise that "shall" and "should" have very specific meanings. "Shall" means it _is_ the case while "should" only indicates that it, well, _should_ be the case, but isn't necessarily. See appendix H of the ISO/IEC directives which POSIX follows as well: http://www.iec.ch/tiss/iec/Directives-Part2-Ed5.pdf
paxdiablo