David Catchpole has asked for the wisdom of the Perl Monks concerning the following question:

I'm a big fan of opening the Command Prompt in Windows and entering a single command line to run a script e.g.
C:\WINDOWS>perl c:\mydocu~1\david\somescript.pl
Now, problem with this is that it sets as the current working directory the directory (e.g. C:/WINDOWS/) I launched the command from, rather than the directory (e.g. C:/My Documents/David/) where the script resides, which I would like to have on hand in order to play with other files that live in its neighbourhood. I guess I'd also like to have fully portable code that's prepared for any reasonable method of launch, and so I think this is an issue that can't be resolved just by changing my own behaviour. Previously I was using Windows 98SE and I'd gone some way to solving the problem by stripping the script path from
$ENV{"CMDLINE"}
... but now I'm using Windows XP, which don't got
$ENV{"CMDLINE"}
or anything similar! Is there any consistent way of getting the full shell command line, or more generally of getting a script to find itself on the file system? Also, what issues does this have for portability to non-Windows OSs?

Replies are listed 'Best First'.
Re: Having a script find itself on the file system in Windows XP and other OSs
by Anonymous Monk on Feb 24, 2004 at 23:24 UTC

    Check out $0.

      Ahhh.... Bugger, now I feel like a dickhead!
Re: Having a script find itself on the file system in Windows XP and other OSs
by matija (Priest) on Feb 25, 2004 at 08:02 UTC
    For simple cases, $0 is the correct answer.

    For more complex cases, you can use FindBin module.

    FindBin exports the following variables:

     $Bin         - path to bin directory from where script was invoked
     $Script      - basename of script from which perl was invoked
     $RealBin     - $Bin with all links resolved
     $RealScript  - $Script with all links resolved
    
    
    I've seen FindBin used in programs which try to work out of the box regardless of the OS they've been run on. MRTG - multi router traffic grapher is one example.