I have a perl script which I have written to search files present in my windows folders, recursively. I enter the search text as the perl script runtime argument to find a file having this text in it's name. The perl script is as below:
use Cwd;
$file1 = @ARGV[0];
#@res1 = glob "*test*";
#@res1 = glob "$file1*";
@res1 = map { Cwd::abs_path($_) } glob "$file1*";
foreach (@res1)
{
print "$_\n";
}
But this is not searching all the sub-directories recursively. I know glob
doesn't match recursively.
So tried using module File::Find
and the function find(\&wanted, @directories);
But I got a error saying find()
undefined. From what I read from help, I thought find()
function is defined by default in Perl installation, with some basic code to find folders/files. Isn't it correct?
Questions is, in the above perl script, how do I search for files/folders recursively?
Second questions, I found that perldoc <module> help
does not have examples about using a certain function in that module, which would make it clear.
Can you point to some good help/document/book for using various perl functions from different perl modules with clear examples of usage of those module functions.
Another excellent module to use is File::Find::Rule which hides some of the complexity of File::Find while exposing the same rich functionality.
use File::Find::Rule;
use Cwd;
my $cwd = getcwd();
my $filelist;
sub buildFileIndex {
open ($filelist, ">", "filelist.txt") || die $!;
# File find rule
my $excludeDirs = File::Find::Rule->directory
->name('demo', 'test', 'sample', '3rdParty') # Provide specific list of directories to *not* scan
->prune # don't go into it
->discard; # don't report it
my $includeFiles = File::Find::Rule->file
->name('*.txt', '*.csv'); # search by file extensions
my @files = File::Find::Rule->or( $excludeDirs, $includeFiles )
->in($cwd);
print $filelist map { "$_\n" } @files;
return \$filelist;
}
These two pages are all you need to study:
If you don't mind using cpan module, Path::Class can do the work for you:
use Path::Class;
my @files;
dir('.')->recurse(callback => sub {
my $file = shift;
if($file =~ /some text/) {
push @files, $file->absolute->stringify;
}
});
for my $file (@files) {
# ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With