13.1. Removing a File

Earlier, you learned how to create a file from within Perl by opening it for output with a filehandle. Now, we'll get dangerous and learn how to remove a file (very appropriate for Chapter 13, don't you think?).

The Perl unlink function (named for the POSIX system call) deletes one name for a file (which could possibly have other names). When the last name for a file is deleted, and no processes have it open, the file itself is removed. This is exactly what the UNIX rm command does. Because a file typically has just one name (unless you've created hard links), for the most part, you can think of removing a name as removing the file. Given that, here's how to remove a file called fred and then remove a file specified during program execution:

unlink ("fred"); # say goodbye to fred
print "what file do you want to delete? ";
chomp($name = <STDIN>);
unlink ($name);

The unlink function can take a list of names to be unlinked as well:

unlink ("cowbird","starling"); # kill two birds
unlink <*.o>;                  # just like "rm *.o" in the shell

The glob is evaluated in a list context, creating a list of filenames that match the pattern. This is exactly what we need to feed unlink.

The return value of unlink is the number of files successfully deleted. If there's one argument, and it is deleted, the result is one, otherwise it is zero. If there are three filenames but only two could be deleted, the result is two. You can't tell which two, so if you need to figure out which deletion ...

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.