How to check if a file exists in Perl?


In this tutorial, we will take a couple of examples and demonstrate how you can if a file exists or not, with the help of Perl. Let's suppose we have a simple text file called "sample.txt" with the following data −

This is a sample txt file
that contains some content inside it.
TutorialsPoint is simply amazing!

We will use a Perl code to check whether this file exists or not.

Example 1

The most basic approach to check whether a file exists or not is to use the "-e" flag and then pass the name of the file. Consider the code shown below.

use warnings; use strict; my $filename = 'sample.txt'; if (-e $filename) { print "the file exists\n"; } else { print "the file does not exist!\n"; }

Save the program code as "sample.pl" and then run the code using the following command −

perl sample.pl

Example 2

We can also add more specific cases to check if a file contains any data, if it exists. In the following example, we will check both the cases, with minimum level of code. The "-s" flag in the code helps us in this regard.

use warnings; use strict; my $filename = 'sample.txt'; if (-e $filename) { print "the file exists\n"; } else { print "the file does not exist!\n"; } if (-s $filename) { print "the file exists and contains some data inside it\n"; } else { print "the file exists but doesn't contain any data inside it\n"; }

Again, save the file as "sample.pl" and run it using the following command

perl sample.pl

Conclusion

In addition to "-e" and "-s", there are other flags such as "-r" that checks if a file is readable, "-x" that checks if a file is executable, "-d" that checks if a file is a directory, etc. In this tutorial, we used two simple examples to show how you can use a Perl code to check if a file exists or not.

Updated on: 14-Mar-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements