Filehandles
A filehandle is the name for an I/O connection between your Perl process and the operating system. Filehandle names are like label names, but use their own namespace. Like label names, the convention is to use all uppercase letters for filehandle names.
Every Perl program has three filehandles that are
automatically opened:
STDIN, STDOUT, and STDERR.
By default, the print and write
functions write to STDOUT.
Additional filehandles are created using the open function:
open (DATA, "numbers.txt");
DATA is the new filehandle that is attached to the external file, which is now opened for reading. You can open filehandles for reading, writing, and appending to external files and devices. To open a file for writing, prefix the filename with a greater-than sign:
open(OUT, ">outfile");
To open a file for appending, prefix the filename with two greater-than signs:
open(LOGFILE, ">>error_log");
The open function returns true if the file is successfully opened,
and false if it failed to open.
Opening a file can fail for any number of reasons: a file does
not exist, is write-protected, or you don’t have permission for a file or directory.
However, a filehandle that has not been successfully opened can still be
read from (giving you an immediate EOF) or written to, with no noticeable effects.
You should always check the result of open immediately and report an
error if the operation does not succeed. The warn function can report an error to standard error if something goes ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access