Recursing down directories

The built-in functions described above do not enable you to easily recurse through subdirectories. Luckily, the File::Find module is part of the standard library distributed with Perl 5.

The File::Find module is documented in chapter 7 of the Camel, on page 439, or in perldoc File::Find.

File::Find emulates Unix's find command. It takes as its arguments a block to execute for each file found, and a list of directories to search.

#!/usr/bin/perl -w

use strict;
use File::Find;

print "Enter the directory to search: ";
chomp(my $dir = <STDIN>);

find (\&wanted, $dir);

sub wanted {
        print "$_\n";
}

For each file found, certain variables are set. $File::Find::dir is set to the current directory name, $File::Find::name contains the full name of the file, i.e. $File::Find::dir/$_.

Exercises

  1. Modify the simple script above (in your scripts directory as exercises/find.pl) to only print out the names of plain text files only (hint: use file test operators)

  2. Now use it to print out the contents of each text file. You'll probably want to pipe your output through more so that you can see it all. (Answer: exercises/answers/find.pl)