How to Tell if a File Exists in Perl

If Your Script Requires a Specific Log or File, Confirm It Exists

Archive
Nikada / 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 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) is only 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. 

Format
mla apa chicago
Your Citation
Brown, Kirk. "How to Tell if a File Exists in Perl." ThoughtCo, Oct. 29, 2020, thoughtco.com/telling-if-file-exists-in-perl-2641090. Brown, Kirk. (2020, October 29). How to Tell if a File Exists in Perl. Retrieved from https://www.thoughtco.com/telling-if-file-exists-in-perl-2641090 Brown, Kirk. "How to Tell if a File Exists in Perl." ThoughtCo. https://www.thoughtco.com/telling-if-file-exists-in-perl-2641090 (accessed March 19, 2024).