Perl Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 5.00

File Test Operators

This section provides a tutorial example on using file test operators to return information about a file or a directory in the file system. For example, -e tests if a file exists or not.

Perl offers a number of unary operators to return statistics of a file or a directory in the file system. Some commonly used ones are:

  • "-e path_name" returns 1, if the path name exists.
  • "-z path_name" returns 1, if the path name has zero size.
  • "-s path_name" returns the size of the path name.
  • "-f path_name" returns 1, if the path name is a file.
  • "-d path_name" returns 1, if the path name is a directory.
  • "-T path_name" returns 1, if the path name is a text file.
  • "-B path_name" returns 1, if the path name is a binary file.

Here is a tutorial example script of using file test operators:

#- FileTestOperators.pl
#- Copyright (c) 2002 by Dr. Herong Yang, http://www.herongyang.com/
#
   print -e "/windows", "\n";             # 1
   print -d "/windows", "\n";             # 1
   print -f "/windows", "\n";             #
   print -e "/windows/test", "\n";        #
   print -e "/windows/system.ini", "\n";  # 1
   print -d "/windows/system.ini", "\n";  #
   print -f "/windows/system.ini", "\n";  # 1
   print -s "/windows/system.ini", "\n";  # 231
   print -z "/windows/system.ini", "\n";  #
   print -T "/windows/system.ini", "\n";  # 1
   print -B "/windows/system.ini", "\n";  #

If you run it on a Windows system, you will get something similar to this:

1
1


1

1
231

1

Sections in This Chapter

Built-in Functions to Work with the File System

File Test Operators

stat() - Returns File Statistics

Dr. Herong Yang, updated in 2008
File Test Operators