Well, with respect to maintainability, I would think that File::Find would be much easier to maintain, once you understand how it works.
As for your code, the problem is the line
my @files = readdir(DIR) || die "Unable to read $workdir: $!\n";
The || operator has a higher precedence than the assignment, which means the readdir() gets evaluated in a scalar context; i.e., it returns only one directory entry. Try the or operator, for the effect you're looking for:
my @files = readdir(DIR) or die "Unable to read $workdir: $!\n";
(Now, if you had been using File::Find, you wouldn't have had to figure this out ;-) ...)
| [reply] [d/l] [select] |
Someone with little or no experience with Perl is going to find it impossible to maintain your code as you have it above. Even we are having a hard time with it.
use File::Find;
use strict;
my $start_from = 'c:\mydocu~1';
if (shift(@ARGV) =~ /all/) {
find(\&search_all, $start_from);
} else {
find(\&search_none, $start_from);
}
sub search_all {
unlink if /\.\d+\w+\-\d+\wm$|\.log$/i;
}
sub search_none {
unlink if /\.\d+\w+\-\d+\wm$/i;
}
Note that I'm not having it print "No files to delete". If you want that feature you'll have to set a flag or something when you delete something, and check for that flag when your script exits. As you're doing it in your code, you'll get a "No files to delete" message for every file that does not match your regexp criteria, which is probably not what you want. | [reply] [d/l] |
That is a much easier way of doing it. One question, how do you set the flags you are talking about?
I also took a look at the else statements I wrote and you are correct. Why do I want to print out the statement once for everyfile that does not match? So I corrected protion of the code. Once again you are the man, thanks.
curtisb
| [reply] |
my $found_any = 0;
...
sub search_all {
unlink, $found_any++ if /.../;
}
# (repeat for search_none)
print "No files found!\n" unless $found_any;
Make sense? You basically set a flag (a variable) if you find anything to unlink, and when your script is completed, check to see if this variable has a value, and if it doesn't, that means nothing matched, and you can alert the user to this fact. You can go the other way as well:
if ($found_any) {
print "$found_any files deleted.\n";
} else {
print "No files were found to delete.\n";
}
| [reply] [d/l] [select] |