Reputation: 445
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
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
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
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