Pipes | Streams  «Prev  Next»

Lesson 2Perl streams
ObjectivePerl uses Unix Model for Input and Output

Perl uses Unix Model for Input and Output

Given the fact that Perl was originally designed as a system-management tool for Unix, it is not surprising to find that Perl uses the same basic model that Unix uses for input and output. That model is called streams. When you use the open() function in Perl, you are opening a stream:

open(FOO, "<$foo");
while(<FOO>) { print }
close(FOO);

Actually, whenever you write to the console with print(), you are writing to a stream. In fact, these two lines of code are identical (as long as you have not changed the default output stream with select():
print "hello, world!\n";
print STDOUT "hello, world!\n";

The stream called STDOUT is the default output stream for Perl, and it sends its output to the screen, unless it has been redirected.

Opening Perl Stream

There are a number of different ways to open a stream. Here are some of the more common methods:

open(FILE, "<$filename");#opens file $filename for input
open(FILE, ">$filename");  
#opens file $filename for output(replaces file)
open(FILE, ">>$filename"); 
#opens file $filename for output(appends to file)
open(FILE, "+<$filename"); 
#opens file $filename for input and output(file must exist)
open(FILE, "+>$filename"); 
#opens file $filename for input and output(replaces file)
open(PIPE, "| $program");  
#opens a pipe to the standard  input stream of $program
open(PIPE, "$program |");  
#opens a pipe from the standard output stream of $program

You will likely use file streams a lot more frequently than pipes. In the next lesson, we will consider file streams more closely.