summarizes some of the more useful file test operators.
|
As might be expected, if you call any of the operators in Table
without following the operator with a filename, a filename of $_ is assumed.
File test operators are useful to check on the existence or permissions of files before you try to open a filehandle, since you can often diagnose problems before a failed open might cause your program to terminate. For example, before trying to open a file for writing, you can check to see if the file exists, and you have the appropriate permissions:
if(-f $filename){
if(not -w $filename){
print("$filename exists, but is not writable\n");
}
else{
open(FI,">$filename") || die "Couldn't open $filename";
}
}
else{
print("$filename doesn't exist\n");
}
File test operators are very handy if you wish to save a file without
overwriting an existing file of the same name. The following code will create
a filename consisting of a name followed by a period and a number - each time a
like named file is created, it will get a higher number than the last file of the
same name:
$i = 1;
$newname = $filename;
while(-f $newname){
$newname = $filename.$i;
$i++;
}
Another useful feature of the
file test operators is that they
``remember'' the last file on which they were invoked and will reuse that information
when they are called with the unusual argument of a single underscore(_). This
allows
you to use several different operators in succession, without the added overhead
of repeating the file query multiple times. Suppose we wish to write a program
that will list some properties of a file if it exists, or a message that the file
doesn't exist otherwise. One approach is illustrated by the following code.
if(-e $file){
if(-w _){
print "writable\n";
}
if(-x _){
print "executable\n";
}
}
else{
print "$file doesn't exist\n";
}
By using the underscore instead of repeating the filename, perl reuses
the information it obtained when it made the first file query, without having to
consult with the operating system again.