File Tests

Perl provides a number of operators to test for the class, condition, and state of files. These are unary operators that take a file name or file handle as an operand and usually return a boolean value (unless the operator checks the age or size of a file, for example). A file test expression takes the form

operator file_name/file_handle

Typical operations with file tests check if a file's existence, its size, its age, or operations on all files of a certain kind.

Common File Test Operators
-eFile exists.
-dFile is a directory.
-fFile is plain file (not a directory, link, etc.).
-TFile is text file.
-BFile is binary file (not a text file).
-rFile is readable by owner/group of running script.
-wFile is writable by owner/group of running script.
-sSize of file.
-MDays since last modification of file.

Example

Assuming that the following items are located in directory 'test' (output from 'ls ./test'),

19.J29TB1.SA2O.var      new_directory           test.jpg                test.xls
colors.html             test.doc                test.txt

the script,

# script file_test.pl

# program opens a directory, reads it, and prints
# the content to STDOUT

# first, create a variable that holds the path to the directory

$dir = "./test"; # we assume directory is a subdirectory 
                   # of the current working directory

# second, create a directory handle named 'DIR':
# directory handles are created with the opendir() function;
# the first parameter is the name of the handle,
# the second is the path and name of the directory

opendir(DIR, $dir);

# get input from DIR
@content = readdir(DIR); # assign a list of the content to var

# process the directory content
foreach $entry (@content)
{
  $entry = "$dir/$entry";
  if (-d $entry ) # test if it is a directory
  {
      print $entry . " is a directory\n";
  }
  elsif (-f $entry ) # test if it is a file
  {
     print $entry . " is a ";
    
     if (-T $entry ) # test if it is a text file
     {
        print "text file,";
     }
     elsif (-B $entry ) # test if it is a binary file
     {
        print "binary file,";
     }
     else
     {
        print "file of unknown format,";
     }
     print " ". (-s $entry) . " bytes\n"; # get the file size
  } 
}
print "\n";
closedir(DIR);  # for good measure

would create the following output:

./test/19.J29TB1.SA2O.var is a text file, 200 bytes
./test/colors.html is a text file, 51586 bytes
./test/new_directory is a directory
./test/test.doc is a binary file, 19456 bytes
./test/test.jpg is a binary file, 38637 bytes
./test/test.txt is a text file, 14 bytes
./test/test.xls is a binary file, 7168 bytes