Home  >  Article  >  Backend Development  >  How to tell files from directories in Perl

How to tell files from directories in Perl

藏色散人
藏色散人Original
2019-01-21 17:32:415998browse

Suppose you are building a Perl script to traverse the file system and log what it finds. When you open a file handle, you need to know whether you are dealing with an actual file or a directory, which you can treat differently. You want a directory so you can continue parsing the file system recursively. The fastest way to tell a file from a directory is to use Perl's built-in file test operation. Perl has operators that can be used to test different aspects of a file. The -f operator is used to identify regular files rather than directories or other types of files.

How to tell files from directories in Perl

Recommended reference study: "Perl Tutorial"

Use -f file to test the operator

#!/usr/bin/perl -w
$filename = '/path/to/your/file.doc';
$directoryname = '/path/to/your/directory';
if (-f $filename) {
print "This is a file.";
}
if (-d $directoryname) {
print "This is a directory.";
}

First, create two strings: one pointing to the file and the other pointing to the directory. Next, $filename is tested using the -f operator, which checks if something is a file.

This will print "This is a file". If you try the -f operator on a directory, nothing will print.

Then, do the opposite for $directoryname and confirm that it is actually a directory. Combine it with the directory glob to sort which elements are files and which are directories:

#!/usr/bin/perl -w
@files = <*>;
foreach $file (@files) {
if (-f $file) {
print "This is a file: " . $file;
}
if (-d $file) {
print "This is a directory: " . $file;
}
}

This article is about how to distinguish files from directories in Perl. I hope it will be useful to friends who need it. help!

The above is the detailed content of How to tell files from directories in Perl. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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