What I am trying to do is get my program to recurse through a directory and for all of those files within the directory, search each file for the word “ERROR” and then print the instance of it out in a seperate file. I was able to do this without making it recursive, i.e. just entering which files to check manually in the cmd. I was wondering what the proper way to use ARGV when recursing is. Here is my code thus far:
#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
my $dir = "c:/programs";
find(\&searchForErrors, $dir);
sub searchForErrors()
{
my $seen = 0;
if (-f){
my $file = $_;
my @errors = ();
open FILE, $file;
my @lines = <FILE>;
close FILE;
for my $line (@lines){
if (/ERROR/ ){
push(@errors, "ERROR in line $.\n");
print FILE "ERROR in line $.:$1\n" if (/Error\s+(.+)/);
}
open FILE, ">$file";
print FILE @lines;
close FILE;
}
}
}
What I need to know is how I can incorporate ARGV so that the program will read in each file in the directory, perform the search, and then output the results of the search to a file. I hope I have explained my question adequately, if you need any clarification, let me know what is confusing. The more explanation you can give with the answer, the better. Thank you!
ARGVis usually used to iterate over files provided from outside of Perl.But it’s not necessary. You could also do:
I prefer File::Find::Rule, but you could stick with File::Find for reasons that should be obvious if you compare the above snippet with the following snippet:
PS – You’re replacing each file with an exact copy of itself, and you’re populating an array you never use. I omitted that code from my version.