Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find files/folders recursively in Perl script?

Tags:

find

module

perl

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.

like image 678
goldenmean Avatar asked Feb 23 '11 10:02

goldenmean


3 Answers

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;
}
like image 116
Bee Avatar answered Oct 28 '22 19:10

Bee


These two pages are all you need to study:

  • File::Find documentation
  • Beginners guide to File::Find
like image 45
Alessandro Avatar answered Oct 28 '22 21:10

Alessandro


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) {
    # ...
}
like image 27
bvr Avatar answered Oct 28 '22 20:10

bvr