Perl file-reading FAQ: How can I perform a test to see if a file exists with Perl?
You can test to see if a file exists with the Perl -e
file test operator.
A Perl “file exists” example
Here's a short test/example:
$filename = 'tempfile.pl'; if (-e $filename) { print "the file exists\n"; } else { print "the file does not exist!\n"; }
As you can see, to test whether a file exists in Perl, you just use the -e
operator with a test operator, like the if
statement (or an unless
statement, or other operator).
Other file test operators
Instead of just using the Perl -e
operator to see if a file exists, you may want to use one of these other file operators to be a little more specific about what you’re looking for:
-z The file exists and has zero size -s The file exists and has non-zero size
Other ways to write your Perl file tests
There are many ways to write Perl code to test whether a file exists. In addition to the previous example, here are a few different examples of tests you can write.
Here’s an example showing how to die
unless a file you need exists:
die "The file $filename does not exist, and I can't go on without it." unless -e $filename;
Here’s an example showing how to avoid clobbering a file that already exists:
die "The file $filename exists and I don't want to clobber it." if -e $filename;
Summary
I hope these Perl “file exists” test examples have been helpful. For more Perl “file tests” information, search this website, or leave a question in the Comments section below.