O'Reilly logo

Perl for System Administration by David N. Blank-Edelman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required