Perl 文件测试运算符
Perl中的文件测试操作符是一种逻辑操作符,可以返回真或假的值。在Perl中,有许多操作符可以用来测试文件的各种不同方面。例如,要检查一个文件是否存在,可以使用-e运算符。或者,在执行追加操作之前,可以检查一个文件是否可以被写入。这将有助于减少程序可能遇到的错误数量。
下面的例子使用’-e’,存在性操作符来检查一个文件是否存在。
#!/usr/bin/perl
# Using predefined modules
use warnings;
use strict;
# Providing path of file to a variable
my filename = 'C:\Users\GeeksForGeeks\GFG.txt';
# Checking for the file existence
if(-efilename)
{
# If File exists
print("File filename exists\n");
}
else
{
# If File doesn't exists
print("Filefilename does not exists\n");
}
输出:

文件名或文件柄作为参数传递给该文件测试操作符-e。
以下是最重要的文件测试操作符的列表。
| 运营商 | 描述 |
|---|---|
| -r | 检查该文件是否可读 |
| -w | 检查该文件是否可写 |
| -x | 检查该文件是否可执行 |
| -o | 检查该文件是否为有效的UID所拥有 |
| -R | 检查文件是否可由真实的UID读取 |
| -W | 检查文件是否可由真正的UID写。 |
| -X | 检查文件是否可由真实的uid/gid执行。 |
| -O | 检查文件是否为真正的UID所拥有 |
| -e | 检查该文件是否存在 |
| -z | 检查该文件是否为空 |
| -s | 检查文件的大小是否为非零(以字节为单位返回大小)。 |
| -f | 检查该文件是否为纯文本文件 |
| -d | 检查该文件是否是一个目录 |
| -l | 检查该文件是否是一个符号链接 |
| -p | 检查该文件是否是一个命名的管道(FIFO):或者文件柄是一个管道 |
| -S | 检查该文件是否是一个套接字 |
| -b | 检查该文件是否是一个块状特殊文件 |
| -c | 检查该文件是否是一个特殊字符文件 |
| -t | 检查文件句柄是否被打开到一个tty上 |
| -u | 检查该文件是否设置了setuid位 |
| -g | 检查该文件是否设置了setgid位 |
| -k | 检查该文件是否设置了粘性位 |
| -T | 检查文件是否为ASCII文本文件(启发式猜测)。 |
| -B | 检查文件是否是 “二进制 “文件(与-T相反)。 |
你可以将AND逻辑运算符与文件测试运算符结合使用,如下所示。
#!/usr/bin/perl
# Using predefined modules
use warnings;
use strict;
# Providing path of file to a variable
my filename = 'C:\Users\GeeksForGeeks\GFG.txt';
# Applying multiple Test Operators
# on the File
if(-efilename && -f _ && -r _ )
{
print("File filename exists and readable\n");
}
else
{
print("Filefilename doesn't exists")
}
输出:

上面的例子,检查文件是否存在,文件是否为纯文本,是否可读。
极客教程