如何判断Perl中是否存在文件

Perl has a set of useful file test operators that can be used to see whether a file exists or not. Among them is -e, which checks to see if a file exists. This information could be useful to you when you are working on a script that needs access to a specific file, and you want to be sure that the file is there before performing operations. If, for example, your script has a log or a configuration file that it depends upon, check for it first. The example script below throws a descriptive error if a file is not found using this test.

Perl有一组有用的文件测试操作符,可用于查看文件是否存在。 其中有-e ,它检查文件是否存在。 当您使用需要访问特定文件的脚本时,并且在执行操作之前要确保该文件已存在时,此信息可能对您有用。 例如,如果您的脚本具有其依赖的日志或配置文件,请首先进行检查。 如果使用此测试未找到文件,则以下示例脚本将引发描述性错误。


#!/usr/bin/perl
$filename = '/path/to/your/file.doc';
if (-e $filename) {
print "File Exists!";
}

First, you create a string that contains the path to the file that you want to test. Then you wrap the -e (exists) statement in a conditional block so that the print statement (or whatever you put there) is only called if the file exists. You could test for the opposite—that the file does not exist—by using the unless conditional:

首先,创建一个字符串,其中包含要测试的文件的路径。 然后,将-e (exists)语句包装在条件块中,以便仅在文件存在的情况下调用print语句(或放置在其中的任何内容)。 您可以测试相反,该文件不存在,使用,除非条件:


unless (-e $filename) {
print "File Doesn't Exist!";
}

其他文件测试操作员 ( Other File Test Operators )

You can test for two or more things at a time using the "and" (&&) or the "or" (||) operators. Some other Perl file test operators are:

您可以使用“和”(&&)或“或”(||)运算符一次测试两个或多个事物。 其他一些Perl文件测试运算符是:

  • -r checks if the file is readable

    -r检查文件是否可读

  • -w checks if the file is writeable

    -w检查文件是否可写

  • -x checks if the file is executable

    -x检查文件是否可执行

  • -z checks if the file is empty

    -z检查文件是否为空

  • -f checks if the file is a plain file

    -f检查文件是否为纯文件

  • -d checks if the file is a directory

    -d检查文件是否为目录

  • -l checks if the file is a symbolic link

    -l检查文件是否为符号链接

Using a file test can help you avoid errors or make you aware of an error that needs to be fixed. 

使用文件测试可以帮助您避免错误或使您意识到需要修复的错误。

翻译自: https://www.thoughtco.com/telling-if-file-exists-in-perl-2641090

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值