1. Technology

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

By

Man on laptop
Comstock Images/Stockbyte/Getty Images
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;
 }
 } 
  1. About.com
  2. Technology
  3. Perl
  4. Programming Perl
  5. File System
  6. How to Tell Something Is a File or Directory in Perl

©2014 About.com. All rights reserved.