eWebProgrammer eweb  

Pipes | Streams  «Prev  Next»
Lesson 1

Introduction to Pipes and Streams using Perl

This module discusses reading and writing to files and communicating with other programs using Perl Pipes. Some of the subjects you will learn about in this module include:
  1. How streams work
  2. Using file streams
  3. Using pipes to communicate with other programs
  4. Sending email from Perl

In the process, you will build and experiment with the second part of our class project, the email program.
When you are finished with this module you will understand how to use streams and pipes well enough to write your own programs using these techniques.

Simple recipes for opening files and pipes in Perl

Whenever you execute I/O on a file in Perl, you do so through what in Perl is called a filehandle.
A filehandle is an internal name for an external file. It is the job of the open function to make the association between the internal name and the external name, and it is the job of the close function to break that association.
For your convenience, Perl sets up a few special filehandles that are already open when you run. These include STDIN , STDOUT , STDERR , and ARGV . Since those are pre-opened, you can use them right away without having to go to the trouble of opening them yourself:
 print STDERR "This is a debugging message.\n";
 print STDOUT "Please enter something: ";
 $response = <STDIN> // die "how come no input?";
 print STDOUT "Thank you!\n";
 while (<ARGV>) { ... }

Output Handles

STDOUT and STDERR are output handles, and STDIN and ARGV are input handles. They are in all capital letters because they are reserved words in Perl, much like the
  1. @ARGV array and
  2. %ENV hash
Their external associations were set up by your shell.
You will need to open every other filehandle on your own. Although there are many variants, the most common way to call Perl's open() function is with three arguments and one return value:
The following definitions hold:
  1. OK : will be some defined value if the open succeeds, but undef if it fails;
  2. HANDLE: should be an undefined scalar variable to be filled in by the open function if it succeeds;
  3. MODE : is the access mode and the encoding format to open the file with;
  4. PATHNAME : is the external name of the file you want opened.