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

Build IT Knowledge with Current & Trusted Content
Helps Employees Develop & Hone New Technical Programming Skills. Sign Up & Get Full Access.

Six Sigma Certification
100% Online-Six Sigma Certificate from Villanova - Find Out More Now.

Learn Embedded Linux, $349
Hands-on kit teaches fundamentals of embedded Linux development on real target hardware. ARM9 SBC.

Workflow Enabled Help Desk & IT Service Management
Automate service desk activities and integrate processes across IT. Learn more here.

Wanna see your ad here?