Pipes | Streams  «Prev  Next»

Lesson 5Pipes
ObjectiveExamine how Perl Pipes Work

Examine how Perl Pipes Work

A pipe is a type of stream that takes output from one process and sends it to another. In Unix, and some other operating systems, you may use pipes from the command line. You may have seen or used a command like this:
ps -a | more

If you are using DOS/Windows, substitute ps -a | more with dir c: | more. The effect is the same, even though the DOS command shell uses temporary files to simulate pipes.
This is actually two commands piped together. The first command,
ps -a
, lists all the processes currently running. The | character is called a pipe, and it effectively sends the output of the ps command to the input of more, which will show you what was received, a screen at a time.

Pipes in Perl

In Perl, pipes are opened with the open command, and they work just like any other stream. Following is a simple Perl script which pipes its output to more:

#!/usr/bin/perl
open(MORE, "| more");
while(<>) { print MORE }
close MORE;

Alternately, you can open a pipe for input, like this:
#!/usr/bin/perl -w
open(PS, "ps -a |");
while(<PS>) { print }
close PS;

In fact, you can even print from one pipe to another:
#!/usr/bin/perl -w
open(PS, "ps -a |");
open(MORE, "| more");

while(<PS>) { print MORE }
close MORE;
close PS;

Perl Pipe - Exercise

Now that you know how they work, let's take a look at a practical application of pipes in our next lesson.
Click the Exercise link below to run the example programs from this lesson on your server.
Perl Pipe - Exercise