Walking the Filesystem Using the File::Find Module
Now
that we’ve seen the basics of filesystem walking, here’s
a faster and spiffier way to do it. Perl comes with a module called
File::Find
that allows Perl to emulate the Unix
find command. The easiest way to begin using this
module is to use the find2perl command to generate
prototypical Perl code for you.
Tip
find2perl is not always easy to use on non-Unix
Perl ports. For example, MacOS users either will need Macintosh
Programmer’s Workshop (MPW) to run it, or should modify the
code to take @ARGV
from a dialog box. Here’s
a code snippet from Chris Nandor, co-author of MacPerl:
Power and Ease, to do this:
@ARGV = @ARGV ? @ARGV : split "\s", MacPerl::Ask("Arguments?");
All ports do have the File::Find
module that find2perl and
find.pl use, so this should not be a real
problem. We’ll show you how to call it directly later in this
chapter.
For instance, let’s say you need some code to search the
/home
directory for files named
beesknees
. The command line that uses the Unix
find command is:
% find /home -name beesknees -print
Feed the same options to find2perl:
% find2perl /home -name beesknees -print
and it produces:
#!/usr/bin/perl eval 'exec /usr/bin/perl -S $0 ${1+"$@"}' if $running_under_some_shell; require "find.pl"; # Traverse desired filesystems &find('/home'); exit; sub wanted { /^beesknees$/ && print("$name\n"); }
The find2perl-generated code is fairly
straightforward. It loads in the necessary
find.pl
library with ...
Get Perl for System Administration now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.