Current Issue


Table of contents

CD-ROM

Sys Admin and The Perl Journal CD-ROM version 12.0

Version 12.0 delivers every issue of Sys Admin from 1992 through 2006 and every
issue of The Perl Journal from 1996-2002 in one convenient CD-ROM!

Order now!

Sys Admin Magazine > Archives > 2001 > February 2001
Page art

What is That, Anyway?

Randal L. Schwartz

So, you've got a directory full of mixed stuff, or maybe an entire tree of directories. Just what's behind each of those names? Are they directories, symbolic links, or just plain files? And if they're files, are they text files or binary files? And if they're binary files, are they images, executables, or just random garbage?

Perl has many built-in operators to make getting lists of names easy, and also for figuring out what you really have once you know a name.

For example, let's find all the subdirectories within the current directory:

for my $name (glob '*') {
  next unless -d $name;
  print "one directory is $name\n";
}

Here, the glob operator expands to all the non-dot-prefixed names within the current directory, and the -d operator returns true for all those names that are directories.

What if we wanted to do this recursively? We need to step outside of the core Perl, but not very far away. A core-included module called File::Find takes care of nearly all of our recursive directory processing problems. Let's find all directories below the current directory:

use File::Find;
find sub {
  return unless -d $_;
  print "one directory is $File::Find::name\n";
}, ".";

The find subroutine takes a subroutine reference (called a coderef), here provided with the anonymous subroutine constructor. Each name found below . (specified on the last line of this snippet) will trigger an invocation of this subroutine, with $File::Find::name set to the full name, and $_ set to the basename (with the working directory already selected to the directory in which the name is located).




MarketPlace

"Six Sigma" Certification
Villanova Six Sigma Certification 100% Online Program - Free Info.

Project Management-Online
Nation's Leading Online PMP Course From Villanova-Find Out More Now.

Automate Software Builds with Visual Build Pro
Easily create an automated, repeatable process for building and deploying software.

WinDev 12 - Powerful IDE
Develop 10 times faster ! ALM, IDE, .Net, RAD, 5GL, Database, 5GL, 64-bit, etc. Free Express version

Wanna see your ad here?