Perl Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 5.00

open() - Opening File Handles for Input and Output

This section describes various ways to use the open() function to open file handles to input data from files or output data to files, input data from another process or output data to another process.

Input to and output from Perl programs must be done through file handles. File handles are created by calling the open() function in different ways for different situations. Examples are:

1. Open a file handle for input from the file named by an expression:

rc = open(file_handle, expression);

2. Open a file handle for input from the file named by an expression:

rc = open(file_handle, "< ".expression);

3. Open a file handle for output to the file named by an expression:

rc = open(file_handle, "> ".expression);

4. Open a file handle for output to append to the file named by an expression:

rc = open(file_handle, ">> ".expression);

5. Open a file handle for output to and input from the file named by an expression:

rc = open(file_handle, "+> ".expression);

I am not sure how input and output can be managed on the same file. Need to be tested.

6. Open a file handle for input from another process named by an expression:

rc = open(file_handle, expression." |");

In this case, "rc" is the process id forked by this call.

7. Open a file handle for output to another process named by an expression:

rc = open(file_handle, "| ".expression);

In this case, "rc" is the process id forked by this call.

8. Open a file handle for input from the standard input channel, usually the key board:

rc = open(file_handle, "_");

9. Open a file handle for output to the standard output channel, usually the monitor screen:

rc = open(file_handle, ">_");

10. Open a file handle for input from a file named by the scale variable of the same name as the file handle:

rc = open(file_handle);

The above statement is equivalent to rc=open(file_handle,$file_handle).

There are 3 pre-defined file handles:

  • STDIN - A file handle connected to the standard input channel.
  • STDOUT - A file handle connected to the standard output channel.
  • STDERR - A file handle connected to the standard error channel.

File handles are closed by the close function:

rc = close(file_handle);

Sections in This Chapter

open() - Opening File Handles for Input and Output

print() - Printing Output to File Handles

<file_handle> - Reading Data from File Handles

Dr. Herong Yang, updated in 2008
open() - Opening File Handles for Input and Output