How to Tell if a File Exists in Perl

How to Tell if a File Exists in Perl

We are searching data for your request:

Forums and discussions:
Manuals and reference books:
Data from registers:
Wait the end of the search in all databases.
Upon completion, a link will appear to access the found materials.

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.

$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.


  1. Malalmaran

    How interesting that sounds

  2. Abdullah

    Just what you need. An interesting topic, I will participate.

Write a message