Perl: How to delete file?

Today I'm going to tell you how to delete a file, or multiple files using Perl. This very easy when you'll know the exact way. There is a function named 'unlink()' at Perl. This function takes a List of file names, and delete those files.

First I'm going to give an example to delete a single file using a small piece of Perl code. Below code just delete the file that is provided into the variable '$file_name'
use strict;

## Your File name, which you want to delete
my $file_name = "c:\\abc\\bcd\\efgh\\in.txt.bak";
## Using unlink, just delete the file.
unlink($file_name);
Now consider you need to delete multiple files. Actually the 'unlink()' function takes an array/list as a parameter. So that case consider the below code block. This takes few file names into an array and remove those from the Hard Disk.
use strict;

## Your list of files
my @files = ("c:\\1.txt","d:\\2.txt","3.txt");
## Using unlink, just delete the file.
unlink(@files);

To read about more Perl related postings, you can take a look at http://icfun.blogspot.com/search/label/perl, Or you can search my blog for other programming languages.

Comments

Anonymous said…
Was writing a perl script to recurse into directories and delete some specific files. It doesn't delete no matter what I do. Finally I found the problem: I forgot to escape the \. Thanks for the timely example :)