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

I am trying to see if a particular file exists, but can't get this code to work.

$mall_path is a relative link to a root directory
$filename is the file I am interested in
keywords is a directory
if (-e "$mall_path/keywords/$filename") { #file exists - set variable and other things }
Do I need to concatenate this? Use single quotes? etc?
I just want to set a variable now--not try to open the file and catch the exception.

Thanks

(I think I put this in the wrong category, but I won't repost since there are already several responses.)

Update: this is on Unix

Update: I found my stupid mistake--I was passing in the wrong file name. The code above works fine when I am looking for the correct file. Thanks for the help.

Replies are listed 'Best First'.
Re: Testing if file exists
by sgifford (Prior) on Oct 04, 2004 at 22:17 UTC
    The key question is: the path in $mail_path is relative to what? Your Perl script won't necessarily start off in the directory where the program is located. Try running pwd to see if your current working directory is where you expect it to be when your CGI script runs:
    print "DEBUG: `pwd`\n";
    and if not adjust your link accordingly. If it's important to you that your program start off in the directory where it's located, there are various tricks you can use to achieve that; use SuperSearch to find them.
Re: Testing if file exists
by JediWizard (Deacon) on Oct 04, 2004 at 22:00 UTC

    The code posted should work, if the relative path is relative to the current working directory. The -e operator only tells you that the path exists, if you really want to know if it is a file, you should check out the -f operator. Also, if you are working in a windows environment, make sure that $mall_path has any \ escaped to \\ or you may have issues with variable interpolation.

    May the Force be with you
      -e vs -f?

      The references I'm looking at say that:
      -e is true if file exists
      -f is true if file is a plain file

      Is this info out-of-date/incorrect or am I missing something?

        The problem is that -e will return true even if the specified "path" or "file" is actually a directory.

        May the Force be with you
Re: Testing if file exists
by !1 (Hermit) on Oct 04, 2004 at 21:49 UTC

    Try this:

    #!/usr/bin/perl -l use File::Spec; my $file = "$mall_path/keywords/$filename"; print "Checking " . File::Spec->rel2abs($file); if (-e $file) { #file exists - set variable and other things }

    Update: Urg, too much Java earlier today. Changed + to . in print statement. Thanks shenme.