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).
|