13. File and Directory Manipulation
Contents:
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.[ 1 ]
13.1 Removing a FileEarlier, 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, File and Directory Manipulation , don't you think?).
The Perl
unlink ("fred"); # say goodbye to fred print "what file do you want to delete? "; chomp($name = <STDIN>); unlink ($name);
The 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
The return value of foreach $file (<*.bak>) { # step through a list of .bak files unlink($file) || warn "having trouble deleting $file: $!"; }
If
If the foreach (<*.bak>) { # step through a list of .bak files unlink || warn "having trouble deleting $_\: $!"; } |
|