Note the use of the special pseudo-filehandle _: it's used to test the last filehandle tested. See perlfunc for more details of this.if (-d $pathname) { # $pathname exists and is a directory # ... } elsif (-e _) { # $pathname exists, but is NOT a directory # ... } else { # $pathname doesn't even exist # ... }
In any case, testing for existence of a file or a directory is often indicative of a bug. It is almost always better to try to get what you need in a single operation. For instance, instead of saying
do just the open:if (-d $d) { open FILE, "$d/$f" or die "Open failed"; } else { die "No directory $d"; }
open FILE, "$d/$f" or die "Open failed";
Let the operating system make sure your path is OK. The first way is subject to an insiduous race condition: directory $d could be created between the test -d $d and the error message, and the error message would be wrong. This is not too bad; but if some more complex error handling were used, it would be likely to break.
So try not to test if you can do something with -X; just try to do it. If you can't, the OS will let you know.
In reply to Re: How to test if a directory exists?
by ariels
in thread How to test if a directory exists?
by newbie00
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |