Science, Tech, Math › Computer Science How to Tell if a File Exists in Perl If Your Script Requires a Specific Log or File, Confirm It Exists Share Flipboard Email Print Nikada / Getty Images Computer Science Perl PHP Programming Python Java Programming Javascript Programming Delphi Programming C & C++ Programming Ruby Programming Visual Basic View More By Kirk Brown Kirk Brown Computer Science Expert B.A., Abilene Christian University Kirk Brown is a systems software engineer with expertise in Perl, PHP, Ruby, and Python. Learn about our Editorial Process Updated on December 24, 2018 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. Cite this Article 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 June 6, 2023). copy citation Featured Video