How to find files / folders recursively in a Perl script?

I have a perl script that I wrote to search for files present in Windows folders recursively. I enter the search text as an argument to the runl perl script to find a file with that text in it. The perl script looks like this:

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 a recursive search for all subdirectories. I know that glob does not match recursively. Therefore, we tried to use the File::Find module and the find(\&wanted, @directories); function find(\&wanted, @directories);

But I got an error find() undefined. From what I read from the help, I thought that the find() function is defined by default in a Perl installation, with some basic code for finding folders / files. Is not it?

Questions in the above perl script, how can I find files / folders recursively?

Second questions, I found that perldoc <module> help has no examples about using a specific function in this module, which would make it clear.

Can you point out some good help / document / book for using different perl functions from different perl modules with explicit examples of using these module functions.

+7
source share
4 answers

Another great module to use is File :: Find :: Rule , which hides some of the complexity of File :: Find , showing 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; } 
+15
source

These two pages are all you need to learn:

+7
source

An alternative would be to use find2perl to create the start of the script for you. It can include find command, for example,

 find . -type f -name "*test*" -print 

To equivalent perl script. You just put find2perl instead of searching. It uses File :: Find under the hood, but it launches you quickly.

+4
source

If you don't mind using the cpan module, Path :: Class can do your job:

 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) { # ... } 
+3
source

All Articles