📜  珀尔 |文件测试运算符

📅  最后修改于: 2022-05-13 01:55:37.081000             🧑  作者: Mango

珀尔 |文件测试运算符

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。以下是最重要的文件测试运算符的列表:

OperatorDescription
-rchecks if the file is readable
-wchecks if the file is writable
-xchecks if the file is executable
-ochecks if the file is owned by effective uid
-Rchecks if file is readable by real uid
-Wchecks if file is writable by real uid
-Xchecks if file is executable by real uid/gid
-Ochecks if the file is owned by real uid
-echecks if the file exists
-zchecks if the file is empty
-schecks if the file has nonzero size (returns size in bytes)
-fchecks if the file is a plain text file
-dchecks if the file is a directory
-lchecks if the file is a symbolic link
-pchecks if the file is a named pipe (FIFO): or Filehandle is a pipe
-Schecks if the file is a socket
-bchecks if the file is a block special file
-cchecks if the file is a character special file
-tchecks if the file handle is opened to a tty
-uchecks if the file has setuid bit set
-gchecks if the file has setgid bit set
-kchecks if the file has sticky bit set
-Tchecks if the file is an ASCII text file (heuristic guess)
-Bchecks 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")
}

输出:

上面的例子,检查文件是否存在以及文件是否是普通文件以及它是否可读。