1. Technology

How to Tell if a File Exists in Perl

Tutorial

By

Businessman using computer
Comstock Images/Stockbyte/Getty Images

We've already learned how to get the size of a file with Perl using the handy File Test Operators. Now lets take a look at another of their functions by testing to see if a file exists or not. This could be useful in a script that needs access to a specific file, and you want it to be sure that the file is there before performing operations. Say for example your script has a log or a configuration file that it depends on - check for it first and throw a descriptive error if it's not found using this test.

 #!/usr/bin/perl -w
 
 $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 gets 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!";
 } 

©2014 About.com. All rights reserved.