珀尔 |文件测试运算符
Perl 中的文件测试运算符是返回 True 或 False 值的逻辑运算符。 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(-e $filename)
{
# If File exists
print("File $filename exists\n");
}
else
{
# If File doesn't exists
print("File $filename does not exists\n");
}
输出:
文件名或文件句柄作为参数传递给此文件测试运算符-e。以下是最重要的文件测试运算符的列表:
Operator | Description |
---|---|
-r | checks if the file is readable |
-w | checks if the file is writable |
-x | checks if the file is executable |
-o | checks if the file is owned by effective uid |
-R | checks if file is readable by real uid |
-W | checks if file is writable by real uid |
-X | checks if file is executable by real uid/gid |
-O | checks if the file is owned by real uid |
-e | checks if the file exists |
-z | checks if the file is empty |
-s | checks if the file has nonzero size (returns size in bytes) |
-f | checks if the file is a plain text file |
-d | checks if the file is a directory |
-l | checks if the file is a symbolic link |
-p | checks if the file is a named pipe (FIFO): or Filehandle is a pipe |
-S | checks if the file is a socket |
-b | checks if the file is a block special file |
-c | checks if the file is a character special file |
-t | checks if the file handle is opened to a tty |
-u | checks if the file has setuid bit set |
-g | checks if the file has setgid bit set |
-k | checks if the file has sticky bit set |
-T | checks if the file is an ASCII text file (heuristic guess) |
-B | checks if the file is a “binary” file (opposite of -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(-e $filename && -f _ && -r _ )
{
print("File $filename exists and readable\n");
}
else
{
print("File $filename doesn't exists")
}
输出:
上面的例子,检查文件是否存在以及文件是否是普通文件以及它是否可读。