Prev

Perl Notes

Next

Chapter 8.8 Checking a File's Status

It's often useful to know whether a file already exists, if it's readable, writeable, or executeable, and so on. You can combine the use of a conditional with a special set of codes that test for certain file states.

To check a files status:

  1. Type -e to check if the files exists.

    Or type -r to check if it's permissions are such that it can be read.

    Or type -x to check if it's permissions are set such that it can be executed.

    Or type -w to check if its permissions are set such tat it can be written to.

    Or type -d to check if it's a directory.

  2. Type the filename that you're interested in checking. You can use either a scalar variable or a constant. If you use, enclose it in quotation marks.


chdir ("../../logs");

if ( -e $desired_file) {
  open(LOG, $desired_file) || &ErrorMesage;
  @log_lines = <LOG>;
  close(LOG);
  $n=1;
  foreach $line (@log_lines) {
    print "Line # $n is $line";
    $n++;
  }
} else {   
  print "Log does not exist.";
} 

File Test Operators Table

OperatorMeaning
-rFile is readable by effective uid/gid.
-wFile is writable by effective uid/gid.
-xFile is executable by effective uid/gid.
-oFile is owned by effective uid.
-RFile is readable by real uid/gid.
-WFile is writable by real uid/gid.
-XFile is executable by real uid/gid.
-OFile is owned by real uid.
 
-eFile exists.
-zFile has zero size.
-sFile has non-zero size (returns size).
 
-uFile has setuid bit set.
-gFile has setgid bit set.
-kFile has sticky bit set.
OperatorMeaning
-fFile is a plain file.
-dFile is a directory.
-lFile is a symbolic link.
-pFile is a named pipe (FIFO).
-SFile is a socket.
-bFile is a block special file.
-cFile is a character special file.
-tFilehandle is opened to a tty.
 
-TFile is a text file.
-BFile is a binary file (opposite of -T).
 
-MAge of file (at startup) in days since modification.
-AAge of file (at startup) in days since last access.
-CAge of file (at startup) in days since inode change

stat - get a file's status information

stat FILEHANDLE
stat EXPR
stat


Returns a 13-element list giving the status info for a file, either the file opened via FILEHANDLE, or named by EXPR. If EXPR is omitted, it stats $_. Returns a null list if the stat fails. Typically used as follows:

Not all fields are supported on all filesystem types. Here are the meaning of the fields:
(The epoch was at 00:00 January 1, 1970 GMT.)

If stat is passed the special filehandle consisting of an underline, no stat is done, but the current contents of the stat structure from the last stat or filetest are returned. Example:
(This works on machines only for which the device number is negative under NFS.)

In scalar context, stat() returns a boolean value indicating success or failure, and, if successful, sets the information associated with the special filehandle _.


Prev Home Next