in reply to Re: Check if file exists
in thread Check if file exists

... accepts either a filehandle or a directory handle ...

Except that in this case, it's either a file name or a directory name. To use a handle, one would use the first argument of a successful open or opendir:

#!/usr/bin/perl use v5.12; use warnings; my $fn='/etc/passwd'; open my $handle,'<',$fn or die "opening $fn failed: $!"; if (-T $handle) { say "$fn looks like text"; } else { say "$fn does not look like text"; } close $handle;

Of course, to use a handle instead of a name, you first have to open a file or a directory. That won't work if it does not exist, or worse, a previously non-existing file might be created. So using handles instead of names for the -e, -f, -d, and -l tests is very uncommon.


A related problem, especially with the -e and -f tests is TOCTOU: You may get a race condition that may be a security problem. Your program is not the only software that runs on the computer. The operating system may switch to another program, practically at any time. So between -e/-f and a following open, things may change drastically in the filesystem, and your program decides on obsolete information. The best way to avoid this problem is to simply allow open to fail, and check $! in case open fails.

Alexander

--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)