Tweet

Using the Perl unlink() function

Introduction

Use the unlink() function to remove one or more files.

Example 1. Remove one file

The simplest case is using unlink() to remove a single file.

#!/usr/bin/perl

use strict;
use warnings;

my $file_to_remove = 'file.txt';

my $num_removed = unlink $file_to_remove;
print "$num_removed files were removed\n";

Example 2. Remove one file and check for success

Since unlink() returns the number of files successfully deleted and sets $! on error, you can check for the success of your unlink as follows:

#!/usr/bin/perl

use strict;
use warnings;

my $file_to_remove = 'file.txt';

unlink $file_to_remove or die "Unable to unlink $file_to_remove: $!";

What's in an name?

A commonly encountered problem is that the variable containing the filename to remove has been read from a file and unless that variable has been chomp()'ed, it will still contain your operating system's input record separator (a new-line in Unix/Linux). Your program will fail as it tries to delete "file.txt\n" instead of "file.txt". See the chomp() function for how to remove your operating system's line-end character (input record separator), before calling unlink().

Example 3. Remove multiple files

You can use an array to specify multiple files:

#!/usr/bin/perl

use strict;
use warnings;

my @files_to_remove = qw/file1.txt file2.txt file3.txt/;

my $num_removed = unlink @files_to_remove;
print "$num_removed files were removed\n";

Note that in the example above, if one (or more) of the files listed in @files_to_remove could not be deleted for some reason, you would have no easy way of detecting which of the files had problems. The function merely returns the number of files that were successfully deleted. If you were to print the system error string found in $!, you would see that there was an error, but you would not know on which file (or files) the error occurred.

Example 2. Remove multiple files and check for success

One way to get some traction with this problem is to unlink each of the files in a loop, as follows.

#!/usr/bin/perl

use strict;
use warnings;

my @files_to_remove = qw/file1.txt file2.txt file3.txt/;

for my $file (@files_to_remove) {
    if ( -f $file) {
        unlink $file or warn "Unable to remove '$file': $!";
    }
}

Be aware that there is a potential race condition between the the test for the file (-f $file) and the call to unlink that follows it. A more cautious approach might be warranted if the files being deleted have implcations for the security of your application.

Removing directories

Removing directories with unlink() is unsafe, (at least in Unix and Linux systems), and Perl will refuse to let you do this unless you are the superuser and provide a runtime flag. Use rmdir instead.

See also

Or from your command line:
  perldoc -f unlink
  perldoc -f rmdir
[Top]