Perl file test operators (reference)

This reference page provides a list of the most commonly-used Perl file test operators.

Operators to determine whether a file or directory exists

Here are the most common Perl file test operators that can be used to determine whether a file or directory exists:

-e  File or directory name exists
-z  File exists and has zero size
-s  File or directory exists and has non-zero size

All of those tests can be executed as shown in the following source code example:

$filename = 'tempfile.pl';
if (-e $filename) {
    print "the file exists\n";
} else {
    print "the file does not exist!\n";
}

Common file test operators

The following Perl file tests can be used to determine if a file or directory is readable, writable, or executable using these file tests:

-r  File (or directory) is readable by effective uid/gid
-w  File (or directory) is writable by effective uid/gid
-x  File (or directory) is executable by effective uid/gid
-o  File (or directory) is owned by effective uid/gid

These tests say "effective" user-id or group-id, but in most every Perl program I've ever written I have used these.

In more advanced programs you may have to work with the "real" user as opposed to the "effective" user in the previous examples. These operators are defined like this:

-R  File (or directory) is readable by real uid/gid
-W  File (or directory) is writable by real uid/gid
-X  File (or directory) is executable by real uid/gid
-O  File (or directory) is owned by real uid/gid

Determining the type of file

The following Perl file test operators can be used to determine what type of file you are actually looking at. While everything on the filesystem is a "file", these "files" can actually be directories, named pipes, symbolic links, etc.

Here are the file-type operators:

-f  The "file" is a plain file
-d  The "file" is a directory
-l  The "file" is a symbolic link
-S  The "file" is a socket
-p  The "file" is a named pipe (a "fifo")
-b  The "file" is a block-special file (like a disk)
-c  The "file" is a character-special file (like a terminal)

Running these tests

Again, all of these tests can be run like this:

$filename = 'tempfile.pl';
if (-e $filename) {
    print "the file exists\n";
} else {
    print "the file does not exist!\n";
}

or like this:

print "$filename is readable\n" if -r $filename;

or a lot of other ways using Perl's if/then and unless operators.

Complete list

For a complete list of Perl's file test operators visit this page.