1. Home
  2. Computing & Technology
  3. Perl

How to tell if something is a file or a directory in Perl

From , former About.com Guide

Lets 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 since you'll treat them differently - you'll want to glob a directory so you can continue to recursively parse the filesystem. The quickest way to do this is with perl's built in File Test Operators.
#!/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 we create two strings - one pointing at a file and one pointing at a directory. Next we 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 tried the -f operator on the directory, it wouldn't print. Then we do the opposite for the $directoryname and confirm that it is, in fact, a directory. Let's combine this with a directory glob, and 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;
}
}
More Perl Quick Tips
Explore Perl
About.com Special Features

The Best Web Trends of the Decade

A look back at the best innovations, ideas and technologies over the last 10 years, More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Perl
  4. Programming Perl
  5. File System
  6. Perl file or directory tutorial - How to tell if something is a file or a directory in Perl using file test operators.

©2009 About.com, a part of The New York Times Company.

All rights reserved.