1. Perl
  2. Operators
  3. File test
  4. here

Check the existence of the file

To check if a file exists , use the file test operator "-e".

-e $file

Returns a true value if the file exists, a false value if it does not exist. Directories and symbolic links are also treated as files. This is because on Unix, directories are also considered as special files and are considered as files.

Check if the normal file exists

If you want to check if a regular file that is not a directory exists, you can check it with the file test operator "-f".

-f $file

Normal Returns a true value if the file exists, a false value if it does not exist. A normal file is a file that stores data such as a text file or a binary file.

Types of files that can be confirmed to exist

There are also file test operators that can check for the existence of directories and symbolic links.

File type Corresponding file operator
Normal file -f
Directory -d
Symbolic link -l
Named pipe, file handle that is a pipe -p
Socket -S
Block special file -b
Character special file -c

I have put up a link to the explanation page of terms.

Example program

This is an example to check the existence of a file using the file test operator "-e".

use strict;
use warnings;

# Check for the existence of the file.
# -e file name
# -e can be used for directories, files, symbolic links, etc.
# You can check if it exists without distinguishing the .

print "1: Check the existence of the file. -e\n";
my $file_all_type = 'a';

if (-e $file_all_type) {
  print "'$file_all_type' exists.\n";
}
else {print "'$file_all_type' does not exist.\n"}

This is an example to check the existence of a normal file using the file operator -f.

use strict;
use warnings;

# Check the existence of normal files.
# -f file name

print "1: Check the existence of normal files. -f\n";
my $file = 'a.txt';
if (-f $file) {
  print "'$file' exists.\n";
}
else {print "'$file' does not exist.\n"}

Related Informatrion