Skip to Main Content
Perl Cookbook
book

Perl Cookbook

by Tom Christiansen, Nathan Torkington
August 1998
Intermediate to advanced content levelIntermediate to advanced
800 pages
39h 20m
English
O'Reilly Media, Inc.
Content preview from Perl Cookbook

Deleting a File

Problem

You want to delete a file. Perl’s delete function isn’t what you want.

Solution

Use Perl’s standard unlink function:

unlink($FILENAME)                 or die "Can't delete $FILENAME: $!\n";
unlink(@FILENAMES) == @FILENAMES  or die "Couldn't unlink all of @FILENAMES: $!\n";

Discussion

The unlink function takes its name from the Unix system call. Perl’s unlink takes a list of filenames and returns the number of filenames successfully deleted. This return value can then be tested with || or or:

unlink($file) or die "Can't unlink $file: $!";

unlink doesn’t report which filenames it couldn’t delete, only how many it did delete. Here’s one way to test for successful deletion of many files and to report the number deleted:

unless (($count = unlink(@filelist)) == @filelist) {
    warn "could only delete $count of "
            . (@filelist) . " files";
}

A foreach over @filelist would permit individual error messages.

Under Unix, deleting a file from a directory requires write access to the directory,[15] not to the file, because it’s the directory you’re changing. Under some circumstances, you could remove a file you couldn’t write to or write to a file you couldn’t remove.

If you delete a file that some process still has open, the operating system removes the directory entry but doesn’t free up data blocks until all processes have closed the file. This is how the new_tmpfile function in IO::File (see Section 7.5) works.

See Also

The unlink function in perlfunc (1) and in Chapter 3 of Programming Perl ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Perl Best Practices

Perl Best Practices

Damian Conway
Mastering Perl

Mastering Perl

brian d foy
Perl Cookbook, 2nd Edition

Perl Cookbook, 2nd Edition

Tom Christiansen, Nathan Torkington

Publisher Resources

ISBN: 1565922433Supplemental ContentCatalog PageErrata