Home » Howtos » Perlfunc » Unlink function |
Use the unlink()
function to remove one or more files.
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";
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: $!";
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()
.
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.
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 implications for the security of your application.
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.
Or from your command line: perldoc -f unlink perldoc -f rmdir