in reply to Delete files matching pattern

I suggest using File::Find, as it will simplify your problem tremendously.


The Eightfold Path: 'use warnings;', 'use strict;', 'use diagnostics;', perltidy, CGI or CGI::Simple, try the CPAN first, big modules and small scripts, test first.

Replies are listed 'Best First'.
Re^2: Delete files matching pattern
by graff (Chancellor) on May 10, 2005 at 03:14 UTC
    Sorry, but I think that's rather doubtful. The suggestions above that use readdir or globs are really quite simple and compact, in addition to being very direct and easy to comprehend.

    The calling and callback mechanisms for File::Find, in contrast, are relatively Byzantine -- obscure and fraught with traps for the unwary and uninitiated. (Much more study and learning is needed to use File::Find at all, let alone use it effectively.) Not only that, but File::Find tends to consume more run-time than other approaches. It has it's uses, but I don't think this is one of them.

    Speaking of reducing run-time, when adopting one of the glob or readdir approaches above, I'd put the regex match before the "-f" test, since doing a stat on every file will take a little extra time, compared to stat'ing just the ones that match the file name pattern.

      First, I didn't say it would be faster, just simpler. I don't know what you mean about being Byzantine and obscure. It's pretty straightforward to me:

      use File::Find; find(\&matches_regex, '.'); sub matches_regex { return undef unless (m/.+\.txt$/ && -f); unlink $File::Find::name,"\n"; ## scalar contains full path }

      This will find and unlink all TXT files in a tree. Now, that may not be as concise, but I personally found it easier to control and understand than readdir loops. YMMV, I suppose. If performance was the primary goal, I would unequivocally agree that File::Find is probably not what one wants.


      The Eightfold Path: 'use warnings;', 'use strict;', 'use diagnostics;', perltidy, CGI or CGI::Simple, try the CPAN first, big modules and small scripts, test first.