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 -printFeed the same options to find2perl:
% find2perl /home -name beesknees -printand 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access