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

Does a perl program retain in a variable the path in which it resides (example, I put a program into the /home/user/bin directory, but then at a later date move it to /home/user/newbin , I would like to be able to simply use a variable to determine what folder the program itself (not the current working directory) is in.

Replies are listed 'Best First'.
Re: program path
by RazorbladeBidet (Friar) on Feb 25, 2005 at 14:52 UTC
    You can see the program name and path in $0
    --------------
    It's sad that a family can be torn apart by such a such a simple thing as a pack of wild dogs
Re: program path
by Fletch (Bishop) on Feb 25, 2005 at 14:52 UTC

    perldoc perlvar, look for $0; see also perldoc FindBin (or FindBin).

Re: program path
by ZlR (Chaplain) on Feb 25, 2005 at 14:57 UTC
    $0 is a special variable that holds the full path of the script, if you launched it with the full path .
    If you launch it with ./ for example you will not have the full path.
    Strip the file name from the path with File::Basename .

    use cwd will give you the cwd function that returns the current path .

Re: program path
by m-rau (Scribe) on Feb 25, 2005 at 14:54 UTC
    And if you need the path, you can go with
    my ($path, $script) = $0 =~ /^(.*\/)?(.+)/;
Re: program path
by manav (Scribe) on Feb 25, 2005 at 15:57 UTC
    see
    perldoc FindBin
    perldoc "my program lives"

    Manav
Re: program path
by sh1tn (Priest) on Feb 25, 2005 at 18:46 UTC
    In addition to File::Basename:
    # UNIX path ($path, $name) = _path('/etc/shadow'); print "path: $path \t name: $name \n"; # dos path ($path, $name) = _path('c:\windows\system\setup.inf'); print "path: $path \t name: $name \n"; sub _path { $^O =~ /LINUX/i and $_[0] =~ m#(.*)/(.[^/]+)?$#; $^O =~ /32/ and $_[0] =~ m#(.*)\\(.[^/]+)?$#; $1 && $2 ? return $1, $2 : $_[0] }