How to Tell if a File Exists in Perl

Businessman using computer
Comstock Images/Stockbyte/Getty Images

Perl has a set of useful file test operators that can be used to see whether a file exists or not. Among them is -e, which checks to see if a file exists. This information could be useful to you when you are working on a script that needs access to a specific file, and you want it to be sure that the file is there before performing operations. If, for example, your script has a log or a configuration file that it depends upon, check for it first.

The example script below throws a descriptive error if a file is not found using this test.

 #!/usr/bin/perl
 
 $filename = '/path/to/your/file.doc';
 if (-e $filename) {
 print "File Exists!";
 }

First, you create a string that contains the path to the file that you want to test. Then you wrap the -e (exists) statement in a conditional block so that the print statement (or whatever you put there) only is called if the file exists. You could test for the opposite—that the file does not exist—by using the unless conditional:

 unless (-e $filename) {
 print "File Doesn't Exist!";
 } 

Other File Test Operators

You can test for two or more things at a time using the "and" (&&) or the "or" (||) operators. Some other Perl file test operators are:

  • -r checks if the file is readable
  • -w checks if the file is writeable
  • -X checks if the file is executable
  • -z checks if the file is empty
  • -f checks if the file is a plain file
  • -d checks if the file is a directory
  • -l checks if the file is a symbolic link

Using a file test can help you avoid errors or make you aware of an error that needs to be fixed.