Like the shells, Perl provides a number of file test operators (see Table 10.3) to check for the various attributes of a file, such as existence, access permissions, directories, files, and so on. Most of the operators return 1 for true and "" (null) for false.
Operator | Meaning |
---|---|
–r $file | True if $file is a readable file. |
–w $file | True if $file is a writeable file. |
–x $file | True if $file is an executable file. |
–o $file | True if $file is owned by effective uid. |
–e $file | True if file exists. |
–z $file | True if file is zero in size. |
–s $file | True if $file has nonzero size. Returns the size of the file in bytes. |
–f $file | True if $file is a plain file. |
–d $file | True if $file is a directory file. |
–l $file | True if $file is a symbolic link. |
–p $file | True if $file is a named pipe or FIFO. |
–S $file | True if $file is a socket. |
–b $file | True if $file is a block special file. |
–c $file | True if $file is a character special file. |
–u $file | True if $file has a setuid bit set. |
–g $file | True if $file has a setgid bit set. |
–k $file | True if $file has a sticky bit set. |
–t $file | True if filehandle is opened to a tty. |
–T $file | True if $file is a text file. |
–B $file | True if file is a binary file. |
–M $file | Age of the file in days since modified. |
–A $file | Age of the file in days since last accessed. |
–C $file | Age of the file in days since the inode changed. |
[a] If a filename is not provided, $_ is the default.
A single underscore can be used to represent the name of the file if the same file is tested more than once. The stat structure of the previous file test is used.
Code View: (At the Command Line) 1 $ ls -l perl.test -rwxr-xr-x 1 ellie 417 Apr 23 13:40 perl.test 2 $ ls -l afile -rws--x--x 1 ellie 0 Apr 23 14:07 afile (In Script) #!/usr/bin/perl $file=perl.test; 3 print "File is readable\n" if -r $file; print "File is writeable\n" if -w $file; print "File is executable\n" if -x $file; print "File is a regular file\n" if -f $file; print "File is a directory\n" if -d $file; print "File is text file\n" if -T $file; printf "File was last modified %f days ago.\n", -M $file; print "File has been accessed in the last 12 hours.\n" if -M <= 12; 4 print "File has read, write, and execute set.\n" if -r $file && -w _ && -x _; 5 stat("afile"); # stat another file print "File is a set user id program.\n" if -u _; # underscore evaluates to last file stat'ed print "File is zero size.\n" if -z_; (Output) 3 File is readable File is writeable File is executable File is a regular file *** No print out here because the file is not a directory *** File is text file File was last modified 0.000035 days ago. File has read, write, and execute set. File is a set user id program. File is zero size. Explanation
|
[a] Read more about the stat structure in Chapter 18, "Interfacing with the System."