How to Tell a File From a Directory in Perl

Using the -f File Test Operator

Man on laptop
Comstock Images/Stockbyte/Getty Images

Let's say you're building a Perl script to traverse a file system and record what it finds. As you open file handles, you need to know if you're dealing with an actual file or with a directory, which you treat differently. You want to glob a directory, so you can continue to recursively parse the filesystem. The quickest way to tell files from directories is to use Perl's built-in ​File Test Operators. Perl has operators you can use to test different aspects of a file. The -f operator is used to identify regular files rather than directories or other types of files.

Using the -f File Test 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, you create two strings: one pointing at a file and one pointing at a directory. Next, test the $filename with the -f operator, which checks to see if something is a file. This will print "This is a file." If you try the -f operator on the directory, it doesn't print. Then, do the opposite for the $directoryname and confirm that it is, in fact, a directory. Combine this with a directory glob to sort out 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;
}
}​

A complete list of Perl File Test Operators is available online.

Format
mla apa chicago
Your Citation
Brown, Kirk. "How to Tell a File From a Directory in Perl." ThoughtCo, Aug. 26, 2020, thoughtco.com/telling-file-or-directory-perl-2641089. Brown, Kirk. (2020, August 26). How to Tell a File From a Directory in Perl. Retrieved from https://www.thoughtco.com/telling-file-or-directory-perl-2641089 Brown, Kirk. "How to Tell a File From a Directory in Perl." ThoughtCo. https://www.thoughtco.com/telling-file-or-directory-perl-2641089 (accessed March 28, 2024).