When using Perl file :: Find a quick and easy way to limit search depth?
2 answers
This perlmonks node explains how to implement mindepth and maxdepth from GNU search.
Basically, they count the number of forward slashes in the directory and use that to determine the depth. The preprocess function will only return values ββwhere the depth is less than max_depth.
my ($min_depth, $max_depth) = (2,3);
find( {
preprocess => \&preprocess,
wanted => \&wanted,
}, @dirs);
sub preprocess {
my $depth = $File::Find::dir =~ tr[/][];
return @_ if $depth < $max_depth;
return grep { not -d } @_ if $depth == $max_depth;
return;
}
sub wanted {
my $depth = $File::Find::dir =~ tr[/][];
return if $depth < $min_depth;
print;
}
Individual approach to your business:
use File::Find;
my $max_depth = 2;
find( {
preprocess => \&preprocess,
wanted => \&wanted,
}, '.');
sub preprocess {
my $depth = $File::Find::dir =~ tr[/][];
return @_ if $depth < $max_depth;
return grep { not -d } @_ if $depth == $max_depth;
return;
}
sub wanted {
print $_ . "\n" if -f; #Only files
}
+5
source to share
Here's another solution, determining the current depth internally File::Find::find
by counting the number of directories returned File::Spec->splitdir
, which should be more portable than counting the forward slash:
use strict;
use warnings;
use File::Find;
# maximum depth to continue search
my $maxDepth = 2;
# start with the absolute path
my $findRoot = Cwd::realpath($ARGV[0] || ".");
# determine the depth of our beginning directory
my $begDepth = 1 + grep { length } File::Spec->splitdir($findRoot);
find (
{
preprocess => sub
{ @_ if (scalar File::Spec->splitdir($File::Find::dir) - $begDepth) <= $maxDepth },
wanted => sub
{ printf "%s$/", File::Spec->catfile($File::Find::dir, $_) if -f },
},
$findRoot
);
+3
source to share