Perl FAQ: How do I delete a list of files in a Perl script?
This is very similar to deleting one file in a Perl program. You just use Perl's unlink function, but this time pass it a list of filenames. Let's take a look at a simple example.
A simple example
First, create some sample files in the current directory:
touch a b c
(This creates three empty files named
c. You can verify this with the
Next, create a simple Perl program named
deleter.pl that has these contents:
@files = qw( a b c ); unlink @files or die "Could not delete all of the files in @files\n";
Deleting files using a wildcard
(WARNING: This is very dangerous, be very careful.)
I just looked at the unlink docs, and saw that you can also delete files using wildcard characters. Here's another quick example.
First, make sure you don't have any files in the current directory ending with the extension
.tmp. Then create some more temporary files using that extension:
touch a.tmp b.tmp c.tmp
Now edit the file
deleter.pl to delete all files in the current directory ending with the file extension
Now run the program (with the caveat that yes, this is very dangerous):
And now when you list all the files in the current directory, all your
.tmp files should be gone.
Getting the number of files deleted
While I'm in the neighborhood, it looks like you can also get the number of files that were successfully deleted, like this:
$count = unlink @files;
$count will contain the number of files that were deleted successfully.