How to tell if a file exists in Perl

藏色散人
Release: 2019-02-15 13:39:25
Original
2680 people have browsed it

Perl has a useful set of file test operators that can be used to see if a file exists. There is -e in it, which checks if the file exists. This information may be useful to you when you are working with a script that requires access to a specific file, and you want to ensure that the file exists before performing an operation.

How to tell if a file exists in Perl

For example, if your script has a dependent log or configuration file, check it first. The example script below raises a descriptive error if the file is not found using this test.

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

First, create a string containing the path to the file you want to test. Then 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 can test the opposite - file does not exist - by using an unless condition:

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

Other File Test Operators

You can use "and" (&&) or "or" (|| ) operator tests two or more things at once. Some other Perl file testing operators are:

Check if the file is readable

w Check if the file is writable

-x Check if the file is executable

-zCheck whether the file is empty

fCheck whether the file is a normal file

-dCheck whether the file is a directory

lCheck whether the file is a symbolic link

Using file testing can help you avoid errors or make you aware of errors that need to be fixed.

Related recommendations: "Perl Tutorial"http://www.php.cn/course/list/39.html

This article This article is about the method of determining whether a file exists in Perl. I hope it will be helpful to friends in need!

The above is the detailed content of How to tell if a file exists in Perl. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template