Perl delete - how to delete a file in a Perl script

Perl FAQ: How do I delete a file in a Perl program?

You delete a file in Perl programs using the Perl unlink function. Let’s take a look at a simple example.

A simple Perl delete (unlink) example

First, we need a test file we can delete from our Perl script. Let’s create a sample file in the current directory using the Unix touch command, like this:

touch delete-me.txt

This creates an empty file named delete-me.txt.

Now, we’ll create a really simple Perl file delete program to delete that file. Here’s the source code for our sample program:

unlink('delete-me.txt') or die "Could not delete the file!\n";

I named my program perl-file-delete.pl, so I can now run my program like this:

perl perl-file-delete.pl

After running that program, and again looking at the current directory with the ls command, I can see that my sacrificial file is now gone.

Perl unlink: things can go wrong

Note that things can go wrong when you try to delete a file using the Perl unlink function, hence the or die part of the Perl script shown above. For instance, if you try to delete a file you don’t own, the unlink command will fail. So, use something like the “or die” approach, or take a look at the Perl unlink function docs for more information.