Removing Files
Most of the time, we make files so that the data can stay around for a while. But when the data has outlived its life, it’s time to make the file 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.
Now, 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. So, going 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 as to 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 ...