Perl Files Handling
Filehandles
A filehandle is the name for the connection between your Perl program and the operating system. Filehandles follow the same naming conventions as labels, and occupy their own namespace.
Every Perl program has three filehandles that are automatically opened for it: STDIN, STDOUT, and STDERR:
STDIN | Standard input (keyboard or file) |
STDOUT | Standard output (print and write send output here) |
STDERR | Standard error (channel for diagnostic output) |
Filehandles are created using the open() function:
open(FILE,”filename”);
You can open files for reading, writing, or appending:
open(FILE,”> newout.dat”)
open(FILE,”>> oldout.dat”)
open(FILE,”< input.dat”)
As an aside, under Windows, there are a number of ways to refer to the full path to a file:
”c:\\temp\\file”
‘c:\temp\file’
“c:/temp/file”
It is important to realize that calls to the open() function are not always successful. Perl will not (necessarily) complain about using a filehandle created from a failed open().
This is why we test the condition of the open statement:
open(F,”< badfile.dat”) or die “open: $!”
You may wish to test for the existence of a file or for certain properties before opening it. Fortunately, there are a number of file test operators available:
File test | Meaning |
---|---|
-e file | File or directory exists |
-T file | File is a text file |
-w file | File is writable |
-r file | File is readable |
-s file | File exists and has nonzero length |
These operators are usually used in a conditional expression:
if (-e myfile.dat) {
open(FILE,”< myfile.dat”) or die “open: $!\n”;
}
Even more information can be obtained about a given file using the stat() function.
Using filehandles
After a file has been opened for reading you can read from it using the diamond operator just as you have already done for STDIN:
$_ = <FILE>; or
while (<FILE>) {
statements;
}
To print to your open output file, use the filehandle as the first argument to the print statement (N.B. no commas between the filehandle and the string to print).
print FILE “Look Ma! No hands!\n”;
To change the default output filehandle from STDOUT to another one, use select:
select FILE;
From this point on, all calls to print or write without a filehandle argument will result in output being directed to the selected filehandle. Any special variables related to output will also then apply to this new default. To change the default back to STDOUT, select it:
select STDOUT;
When you are finished using a filehandle, close it using close():
close(FILE);