1. Home
  2. Computing & Technology
  3. Perl

How to tell if a file exists in Perl

From About.com

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!";
}
More Perl Quick Tips
Explore Perl
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Perl
  4. Programming Perl
  5. File System
  6. Perl file exists tutorial - How to tell if a file exists in Perl using file test operators.

©2009 About.com, a part of The New York Times Company.

All rights reserved.