user1440061
user1440061

Reputation: 445

Perl Recurse through Directory

So essentially what I'm trying to do is go through a directory and perform an action on all of the files, in this case, the sub searchForErrors. This sub works. What I have so far is:

sub proccessFiles{
    my $path = $ARGV[2];

    opendir(DIR, $path) or die "Unable to open $path: $!";
    my @files = readdir(DIR);
    @files = map{$path . '/' . $_ } @files;
    closedir(DIR);

    for (@files){
        if(-d $_){
            process_files($_);
        }
        else{
        searchForErrors;
    }
}
}

proccessFiles($path);

Any help/suggestions would be great. And again, I'm new to Perl, so the more explanation the better. Thank you!

Upvotes: 1

Views: 7411

Answers (3)

CowboyTim
CowboyTim

Reputation: 57

A better way of using File::Find without using a lot of memory would be:

use strict; use warnings;
use File::Find;

find(
    sub { 
        searchForErrors($File::Find::name) unless -d
    }, 
    "/tmp/"
);

This is more iterator style.

Upvotes: 1

Borodin
Borodin

Reputation: 126722

I thought it would be useful to show a Path::Class solution in addition to TLP's File::Find one.

I think this is pretty much self-explanatory.

use strict;
use warnings;

use Path::Class 'dir';

my $root = dir 'C:\path\to\root';

$root->recurse(callback => sub {
  my $file = shift;
  searchForErrors($file) unless $file->is_dir;
});

Upvotes: 3

TLP
TLP

Reputation: 67900

You should use the File::Find module instead of trying to reinvent the wheel:

use strict;
use warnings;
use File::Find;

my @files;
my $start_dir = "somedir";  # top level dir to search
find( 
    sub { push @files, $File::Find::name unless -d; }, 
    $start_dir
);
for my $file (@files) {
    searchForErrors($file); 
}

A problem with your current code is that you are including . and .. directories in your recursive search, which will no doubt cause deep recursion errors.

Upvotes: 11

Related Questions