modulereview
Corion
File::Find is the way if you want to look at all files in one or more directories.
<TT>File::Find</TT> exports one function, <TT>find()</TT>, which takes two parameters, a hash or a code reference, and a list of directories where the search starts.
<H2>Why use File::Find</H2>
<P>
File::Find protects you from a lot of nasty things that happen on filesystems. In its standard configuration it ensures that your code reference is called once for each file encountered, even if there are more symlinks pointing to it, and it also prevents nasty loops for symlinked directories.
</P>
<H2>Why avoid File::Find</H2>
<P>
There is not much reason to avoid [cpan://File::Find] - you
could want to avoid it if you want to read files in a single directory, without recursing, when you are explicitly sure that there can be no symlinks in that directory (for example, if the filesystem dosen't allow symlinks). Then, your code could load faster. But I'd file that under premature optimization.
</P>
<H2>Caveats</H2>
<P>
If you are starting to first use File::Find, you have to deal with some idiosyncrasies.
</P>
<p>First of all, File::Find uses some "optimization" by default to speed up searches under certain filesystems under Unix. Unfortunately, this "optimization" fails to work under other filesystems, such as the <tt>iso9600</tt> filesystem used for cdroms. [ncw] tells you below what to do about it - in fact, you should always use the code [ncw] proposes.</p>
<P>
In the default configuration, the directory is changed to the recursed directory, and all returned filenames are relative to the current directory. Use <TT>$File::Find::name</TT> to get a fully specified filename.
</P>
<P>
If you don't want to recurse below a certain directory, there is the (not-so-well-documented) <TT>$File::Find::prune</TT> variable, which you can set to 1 in your code reference to stop recursing into the current directory.</P>
<h2>Examples</h2>
<p>By popular demand, here are some examples on how to use
the module. The [perlman:File::Find|documentation] shows off some interesting code, but it's not helpful if you're looking for something to get started.</p>
<p>A first example, printing the filename and the filename with the path to the file. The code was stolen from a
[id://1317|node] by [nate].</p>
<code>
use strict;
use File::Find;
sub eachFile {
my $filename = $_;
my $fullpath = $File::Find::name;
#remember that File::Find changes your CWD,
#so you can call open with just $_
if (-e $filename) {
print "$filename exists!"
. " The full name is $fullpath\n";
}
}
find (\&eachFile, "mydir/");
</code>
Enumerate files and directories in a directory tree
Use this module instead of globbing or readdir()