← Back to Perl Course | Chapter 5: File I/O | Lesson 5 of 7

File tests

Short operators such as -e and -d ask questions about a file before you use it.

In this page:

  1. File tests

File tests

The file test operators check a path without opening it: -e tests that it exists, -f that it is a plain file, -d that it is a directory, -s returns its size (or false if empty), and -r, -w and -x test permissions. They return true or false, so they fit naturally in an if statement. Two related functions, rename and unlink, move and delete files.

Note: A test such as -s returns the size in bytes, which is false for an empty file.

Example: File tests

perl
use strict;
use warnings;

my $file = "demo_tests.txt";
open(my $fh, '>', $file) or die "Cannot write: $!";
print $fh "12345\n";
close $fh;

print "exists: ", (-e $file ? "yes" : "no"), "\n";
print "plain file: ", (-f $file ? "yes" : "no"), "\n";
print "directory: ", (-d $file ? "yes" : "no"), "\n";
print "size: ", -s $file, "\n";
print "readable: ", (-r $file ? "yes" : "no"), "\n";

rename $file, "demo_renamed.txt" or die "Cannot rename: $!";
print "old name exists: ", (-e $file ? "yes" : "no"), "\n";
print "new name exists: ", (-e "demo_renamed.txt" ? "yes" : "no"), "\n";
unlink "demo_renamed.txt";
print "after unlink: ", (-e "demo_renamed.txt" ? "exists" : "gone"), "\n";

# Output:
# exists: yes
# plain file: yes
# directory: no
# size: 6
# readable: yes
# old name exists: no
# new name exists: yes
# after unlink: gone
Common Mistakes
  1. Confusing -e (exists) with -f (plain file)
  2. Assuming -s returns true for an empty file
  3. Checking a file and then opening it, forgetting that it can change in between
Chapter Summary
  • -e exists, -f plain file, -d directory
  • -s returns the size
  • -r -w -x check permissions
  • rename and unlink move and delete
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.