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

Hi Monks,
I have the code below that will give me the current directory, I am using it to open files without having to type the entire path to it, but I am having a problem where I need to access a file that is in a different location on my directory structure, how can I open a file using similar code to open a file in a different location like one directory lower from where this code is?
Thanks.
BEGIN { $0 =~ '(.*[\\\/])\w+\.\w+$'; $curr_dir = $1 || "./"; }

Replies are listed 'Best First'.
Re: Recursive Path
by jpeg (Chaplain) on May 27, 2005 at 20:09 UTC
    That code isn't reliable, nor is it designed to be. perldoc perlop perlvar will tell you that $0 is the name of the currently running script. It isn't supposed to be the current working directory and that assumption is easily broken by calling a script from another directory.

    Use the core module Cwd if you need the current directory. Use another core module, File::Find if you want to process files from there.

    HTH.

    Update:
    D'oh, $0 and other fun variables are documented in perldoc perlvar, not perldoc perlop.

    --
    jpg
Re: Recursive Path
by djohnston (Monk) on May 27, 2005 at 20:03 UTC
    I use File::Spec::Functions qw(catfile), then I call catfile to append stuff to the path, like this: catfile( $curr_dir, 'subdir' ).
      I believe this is not necessary. It is usually sufficient just to use '/' - Perl will figure it out. File::Spec is only needed when you need filenames that can be passed to external programs that require them to be expressed in the host OS's syntax.
Re: Recursive Path
by nobull (Friar) on May 28, 2005 at 07:40 UTC
    You are confusing 'current directory' with 'directory where the script is'.

    You have rolled you own poor man's FindBin but you do not need to be a poor man - FindBin is standard.