Perl Files Handling
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:
You can open files for reading, writing, or appending:
As an aside, under Windows, there are a number of ways to refer to the full path to a 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:
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:
|-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:
Even more information can be obtained about a given file using the stat() function.
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:
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).
To change the default output filehandle from STDOUT to another one, use select:
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:
When you are finished using a filehandle, close it using close():