File::Find -- using a module
An example of a module included with Perl is File::Find
. There are several
modules under the File::Find
section, such as File::Basetree
, File::Compare
and File::Stat
.
This is an example of how File::Find
can be used:
use File::Find; $dir1='/some/dir/with/lots/of/files'; $dir2='/another/directory/'; find(\&wanted, $dir1,$dir2); sub wanted { print "Found it $File::Find::dir/$_\n" if /^[a-d]/i; }
The first line is the most important. The use
function
loads the File::Find
module. Now, all the power and functionality of File::Find
is available for use. Such as the find
function. This accepts two basic
parameters:
- The name of a subroutine, usually
wanted
which defines what you want to do with the list of files being returned. The filename will be in$_
. - A list of directories to be searched. Subdirectories will also be searched.
The subroutine wanted
simply prints the directory the file was found in if
the filename begins with a,b,c or d. Make your own regex to suit. The line $File::Find::dir
means the $dir
variable in the module $File::Find
. This is
explained further in the next section.
Note -- the \&wanted
parameter is a reference to a subroutine.
Essentially, this means that the code in File::Find
knows where to find the &wanted
subroutine. It is basically like shortcuts under Windows 9x and NT4, instead of actual
files (but the UNIX Perl people would slaughter me for that, so be quiet).