We can find out various information about files by using file test operators and functions such as stat()
Table 2-1. File test operators
Operator | Meaning |
---|---|
-e | File exists. |
-r | File is readable |
-w | File is writable |
-x | File is executable |
-o | File is owned by you |
-z | File has zero size. |
-s | File has nonzero size (returns size). |
-f | File is a plain file. |
-d | File is a directory. |
-l | File is a symbolic link. |
-p | File is a named pipe (FIFO), or Filehandle is a pipe. |
-S | File is a socket. |
-b | File is a block special file. |
-c | File is a character special file. |
-t | Filehandle is opened to a tty. |
-u | File has setuid bit set. |
-g | File has setgid bit set. |
-k | File has sticky bit set. |
-T | File is a text file. |
-B | File is a binary file (opposite of -T). |
-M | Age of file in days when script started. |
-A | Same for access time. |
-C | Same for inode change time. |
The file test operators are documented fully in perldoc perlfunc.
Here's how the file test operators are usually used:
#!/usr/bin/perl -w use strict; unless (-e "config.txt") { die "Config file doesn't exist"; } # or equivalently... die "Config file doesn't exist" unless -e config.txt; |
The stat() function returns similar information for a single file, in list form. lstat() can also be used for finding information about a file which is pointed to by a symbolic link.
Write a script which asks a user for a file to open, takes their input from STDIN, checks that the file exists, then prints out the contents of that file. (Answer: exercises/answers/fileexists.pl)
Write a script to find zero-byte files in a directory. (Answer: exercises/answers/zerobyte.pl)
Write a script to find the largest file in a directory: exercises/answers/largestfile.pl)