File Handles

The input/output connections between the operating system and a Perl program are called filehandles; they regulate the transmission of data between the input channels, the central processing unit, and the output channels.

Upon starting a program, Perl automatically opens three filehandels:

The output for the "print" command goes to STDOUT by default.

A filehandle is accessed by using the diamond operator with the filehandle name inserted:

<FILEHANDLE>

A filehandle can be given any name (STDOUT, STDIN, and STDERR are reserved names, of course). Since they are constants (they don't change), they are customarily written in upper-case letters. This help to ensure that their names don't collide with other names defined in the program.

The < > operator is a line-input operator; when it is used in a scalar context on a filehandle it returns a line from the file every time it is called until the end-of-file marker is encountered. If it is called in a list context, it returns an entire file, and each line is one element in the list.

Perl grew out of Unix, and Unix treats everything as a file: files, of course, but also directories, the output monitor, disk drives, CD-ROM drives, everything. Consequently, it doesn't matter what a filehandle is: it can be an actual file, but it might be the keyboard as well. As far as programming is concerned

<MY_FILE>

is handled the same way as

<STDIN>

The only difference is that input in the first case comes from a file, in the second it comes from the keyboard. The details are handled by Perl.