in reply to find function

As I prefer functional style programming over procedural, I never really liked File::Find's "global vars interface".

So being faced with the problem of looking through some directory tree i will use File::Find, but when it's necessary to tweak the process of its search, I prefer using the preprocess CODEref.

As I don't see that covered a lot in the resources given by PodMaster, I'd like to give an (overly explicit) example:

use strict; use warnings; use File::Find; sub wanted { my $file = $File::Find::name; print "$File::Find::name is a ", -d $file ? 'directory' : 'file', $/ +; } sub filter { grep { my $file = "$File::Find::dir/$_"; if (-d $file) { my $depth = $file =~ s#/#/#g; if ($depth > 3) { print "Depth > 3 in $file ... skipping\n"; 0; # return as grep result for this $file } else { 1; # concider this to recurse into } } else { 1; # include non-dirs } } grep !/^\.\.?$/, @_; } find( { no_chdir => 1, wanted => \&wanted, preprocess => \&filter, }, shift );
An additional advantage of this approach over using/setting File::Find::prune, is that it also works with bydepth => 1.

Also note, that I generally refuse to let find do the chdir thing, because that tends to confuse me. ;-)

Just my two eurocent

Replies are listed 'Best First'.
Re^2: find function
by Anonymous Monk on Dec 06, 2005 at 16:09 UTC
    As I prefer functional style programming over procedural, I never really liked File::Find's "global vars interface"

    That's kind of funny. File::Find has one of the most functional interfaces of any core module I can think of. I mean, its 'find' subroutine's first argument is a function. Granted, it does use funky globals instead of @_ to pass arguments to that function, but I think that's an orthogonal to its functional-ness.

      wanted (like find) itself can never be "functional", since its return value ist either discarded or nonexistent, relying entirely on side-effects for their "function" ;-)

      For a clarification what program language designer nick-name "functional" the wikipedia article on Functional_programming is a good start.