Chapter 13. File and Directory Manipulation
This chapter shows you how to manipulate the files themselves, not merely the data contained within. Perl uses UNIX semantics for providing access to files and directories. Some of these names will be familiar to Win32 programmers who have used the C run-time library, while others may not. Perl provides a rich set of file and directory manipulation routines, and not all of these are implemented on Win32 platforms, but we’ll cover the most useful ones here.[83]
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 a file. This is
exactly what the command prompt
del
command does. 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 ("spottedowl","meadowlark"); # kill two birds unlink <*.bak>; # just like "del *.bak" in the command prompt
The glob is evaluated in a list context,
creating a list of filenames that match the pattern. This list is
exactly what we need to feed unlink
.
The return value of unlink
is the number of files successfully deleted. If only one argument ...
Get Learning Perl on Win32 Systems 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.