Perl has many operators that you can use to test different aspects of a file. For example, you can use the -e operator to ensure that a file exists before deleting it. Or, you can check that a file can be written to before appending to it. By checking the feasibility of the impending file operation, you can reduce the number of errors that your program will encounter.
A complete list of the operators:
| Operator | Description |
|---|---|
| -A OPERAND | Returns the access age of OPERAND when the program started. |
| -b OPERAND | Tests if OPERAND is a block device. |
| -B OPERAND | Tests if OPERAND is a binary file. If OPERAND is a file handle, |
| then the current buffer is examined, instead of the file itself. | |
| -c OPERAND | Tests if OPERAND is a character device. |
| -C PERAND | Returns the inode change age of OPERAND when the program started. |
| -d OPERAND | Tests if OPERAND is a directory. |
| -e OPERAND | Tests if OPERAND exists. |
| -f OPERAND | Tests if OPERAND is a regular file as opposed to a directory, |
| symbolic link or other type of file. | |
| -g OPERAND | Tests if OPERAND has the setgid bit set. |
| -k OPERAND | Tests if OPERAND has the sticky bit set. |
| -l OPERAND | Tests if OPERAND is a symbolic link. Under DOS, |
| this operator always will return false. | |
| -M OPERAND | Returns the age of OPERAND in days when the program started. |
| -o OPERAND | Tests if OPERAND is owned by the effective uid. |
| Under DOS, it always returns true. | |
| -O OPERAND | Tests if OPERAND is owned by the read uid/gid. |
| Under DOS, it always returns true. | |
| -p OPERAND | Tests if OPERAND is a named pipe. |
| -r OPERAND | Tests if OPERAND can be read from. |
| -R OPERAND | Tests if OPERAND can be read from by the real uid/gid. |
| Under DOS, it is identical to -r. | |
| -s OPERAND | Returns the size of OPERAND in bytes. |
| Therefore, it returns true if OPERAND is non-zero. | |
| -S OPERAND | Tests if OPERAND is a socket. |
| -t OPERAND | Tests if OPERAND is opened to a tty. |
| -T OPERAND | Tests if OPERAND is a text file. If OPERAND is a file handle, |
| then the current buffer is examined, instead of the file itself. | |
| -u OPERAND | Tests if OPERAND has the setuid bit set. |
| -w OPERAND | Tests if OPERAND can be written to. |
| -W OPERAND | Tests if OPERAND can be written to by the real uid/gid. |
| Under DOS, it is identical to -w. | |
| -x OPERAND | Tests if OPERAND can be executed. |
| -X OPERAND | Tests if OPERAND can be executed by the real uid/gid. |
| Under DOS, it is identical to -x. | |
| -z OPERAND | Tests if OPERAND size is zero. |
Note:
If the OPERAND is not specified in the file test, the $ variable will be used instead.
Example:
$filename = '/path/to/your/file.doc';
$directoryname = '/path/to/your/directory';
if (-f $filename) {
print "This is a file.";
}
if (-d $directoryname) {
print "This is a directory.";
}
No comments:
Post a Comment