in reply to Check if file exists

If $image is '' or undefined, then $file would be "F:/images/". If the directory F:/images exists, then -e would be true. If you used "use warnings;" you'd at least get a warning in the undefined case.

I'd suggest also using -f instead of -e, as -f would be true only if it exists and is a file rather than a directory:

$ perl u.pl Use of uninitialized value $file in concatenation (.) or string at u.p +l line 16. Use of uninitialized value $file in concatenation (.) or string at u.p +l line 21. OK, missing OK, missing OK, OK $ cat u.pl use strict; use warnings; my $f1; my $f2=''; my $f3='README'; my $dir='./xyz'; print chk($dir, $f1), ", ", chk2($dir,$f1),"\n"; print chk($dir, $f2), ", ", chk2($dir,$f2),"\n"; print chk($dir, $f3), ", ", chk2($dir,$f3),"\n"; sub chk { my ($dir, $file) = @_; return -e "$dir/$file" ? "OK" : "missing"; } sub chk2 { my ($dir, $file) = @_; return -f "$dir/$file" ? "OK" : "missing"; }

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Replies are listed 'Best First'.
Re^2: Check if file exists
by Anonymous Monk on May 07, 2018 at 12:34 UTC
    Thanks!

    Tried and rhe results are as expected.

    I'm curious why is -e is what I usually see for file existence checking and not -f?
      I'm curious why is -e is what I usually see for file existence checking and not -f?

      I'd say it's probably because -f can be a little too restrictive:

      $ perl -le 'print -f "/dev/null" ? "IS" : "is NOT", " a file"' is NOT a file

      but it's also true that sometimes -e gets overused when a more restrictive check would have been better, for example at least checking ! -d.

      Update: Just to clarify what I meant with the above example: If a user is supposed to supply a filename to a program, then in a lot of cases the program shouldn't reject /dev/null and just work with it as if it was a regular file. Of course there might be cases where a program would want to accept only regular files - but then again, -f also returns true if what's being tested is a symbolic link to a file, so one would have to check for that specially too.