Removing Files

Most of the time, we make files so the data can stay around for a while. But when a file is no longer needed, it’s time to make it go away. At the Unix shell level, we’d type an rm command to remove a file or files:

    $ rm slate bedrock lava

In Perl, we use the unlink operator:

    unlink "slate", "bedrock", "lava";

This sends the three named files away to bit heaven, never to be seen again.

Since unlink takes a list, and the glob function returns a list, we can combine the two to delete many files at once:

    unlink glob "*.o";

This is similar to rm *.o at the shell, except that we didn’t have to fire off a separate rm process. So, we can make those important files go away that much faster.

The return value from unlink tells us how many files have been successfully deleted. Back to the first example, we can check its success:

    my $successful = unlink "slate", "bedrock", "lava";
    print "I deleted $successful file(s) just now\n";

Sure, if this number is 3, we know it removed all of the files, and if it’s 0, then we removed none of them. But what if it’s 1 or 2? Well, there’s no clue which ones were removed. If you need to know, do them one at a time in a loop:

    foreach my $file (qw(slate bedrock lava)) {
      unlink $file or warn "failed on $file: $!\n";
    }

Here, each file being deleted one at a time means the return value will be 0 (failed) or 1 (succeeded), which happens to look like a nice Boolean value, controlling the execution of warn. Using or warn is similar to or die, except that ...

Get Learning Perl, Fourth 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.