Take the 2-minute tour ×

How can I get the name of the script?

For example, I have a perl script with the name XXX.pl. This file contains:

$name = #some function that obtains the script's own name
print $name;



I would like to liken this to the CWD function that obtains the scripts directory. I need a function that obtains the script's name as well. Thanks!

share|improve this question

3 Answers 3

up vote 40 down vote accepted

The name of the running program can be found in the $0 variable:

print $0;

man perlvar for other special variables.

share|improve this answer
SO offers some nice formatting, I edited for you so you can take a look at the edit diff for what you can do. –  DVK Jan 5 '11 at 3:30
thanks! first couple of responses. still learning the tools. –  Zac Sprackett Jan 5 '11 at 3:39
use File::Basename;
my $name = basename($0);

PS. getcwd() and friends don't give you the script's directory! They give you the working directory. If the script is in your PATH and you just call it by name, not by its full path, then getcwd() won't do what you say. You want dirname($0) (dirname also is in File::Basename).

share|improve this answer

You might also be interested in learning more about __FILE__, and possibly __LINE__, which gives you the current line and I frequently use together.

If you want this for debugging purposes, you might also want to learn about "warn", "Carp", "caller".

share|improve this answer

Your Answer


