Herong's Tutorial Notes on Perl - Part A
Dr. Herong Yang, Version 4.09

Input to and Output from Perl Programs

Part:   1   2 

This chapter describes:

  • How to open files for input and output.
  • How to print out data to an output channel.
  • How to read in data from an input channel.

Opening File Handles for Input and Output

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_name).

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);

(Continued on next part...)

Part:   1   2 

Dr. Herong Yang, updated in 2006
Herong's Tutorial Notes on Perl - Part A - Input to and Output from Perl Programs