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

when we check if a file exists using -e <filename> do we need to provide a complete path or just the file name, in case of just the file name where will perl search for the file. does it take into consideration any environment variable or will it only search in current directory.

Replies are listed 'Best First'.
Re: search for a file
by japhy (Canon) on Jun 08, 2006 at 12:37 UTC
    Perl does not look in your PATH environment variable for files. It looks in the current directory, unless you give it a FULL file path.

    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
      That depends on what the meaning of "is" is. Erm, I mean...

      You can do -e '../foo/bar', which checks a file in a different directory, but I don't consider a relative path to be "a FULL file path" either. That's just semantics, I know, but it seemed like something worth clarifying in case the OP reads your comment the way I did.

      To the OP: It works like filename arguments (which ignore $PATH), not executable filenames (which search $PATH). ls foo only looks in the current directory, ls /bin/foo only looks in /bin, and ls ../bar/foo only looks in ../bar. -e works the same way.

Re: search for a file
by liverpole (Monsignor) on Jun 08, 2006 at 13:03 UTC
    Of course, you can always use an environment variable to construct the path, if that's what you need:
    use strict; use warnings; (my $file = shift) or die "No file specified.\n"; my $dir = $ENV{'USER_PATH'} || "."; # Use current directory if USER +_PATH not set my $path = "$dir/$file"; # Construct full pathname

    s''(q.S:$/9=(T1';s;(..)(..);$..=substr+crypt($1,$2),2,3;eg;print$..$/
Re: search for a file
by sgifford (Prior) on Jun 08, 2006 at 18:23 UTC
Re: search for a file
by girarde (Hermit) on Jun 08, 2006 at 16:11 UTC
    I cannot imagine being willing to search the path when checking for a file's existence unless what I really wanted to know was "is another file of the same name somewhere in the path that I wasn't expecting, and that's why it runs so weird?"

    If I want to know if a particular file exists I always specify where to look, or else use find/dir. Which is likely to turn up instances that could interfere with execution even if NOT in the path per se.

Re: search for a file
by leocharre (Priest) on Jun 08, 2006 at 15:25 UTC

    Full path. You can can use $ENV{HOME} to help out, if it is set. Also consider:

    • -f "/your/file here", returns true of it is a "file"
    • -d "/your/path/to a dir", returns true if node is a dir