Perl Scripting: Check If a File Exists

It's not often that I write about Perl Scripting on Unix Tutorial, but that's just because I don't script in Perl this much on a regular basis. Today, however, I'd like to share one of the building blocks – a really basic piece of functionality which you'll find really useful in almost any Perl script.

How to check if a file exists in Perl

First of all, we need to create one file for our experiments:

ubuntu$ touch /tmp/file.try

Now, create a new file with our script: /tmp/ (don't forget to chmod a+x /tmp/ afterwards to make it executable):

if (-e $FILE1) {
        print "File $FILE1 exists!\n";} else {
        print "File $FILE1 is not found!\n";
if (-e $FILE2) {
        print "File $FILE2 exists!\n";
} else {
        print "File $FILE2 is not found!\n";

Now, as you can see from the example, the actual condition checking for the existence of a file is this:

if (-e $FILE)

where $FILE is the string containing the filename.

In my example, there's two filenames ($FILE1 and $FILE2) and two conditions, so that you can see for yourself how one of them confirms the existence of a file and another one proves that there's no such file found.

To see the script work, simply run it without any parameters:

ubuntu$ /tmp/
File /tmp/file.try exists!
File /tmp/file2.try is not found!

That's all for today! Enjoy your Perl scripting!

See also: