Pipes

A pipe is a unidirectional I/O channel that can transfer a stream of bytes from one process to another. Pipes come in both named and nameless varieties. You may be more familiar with nameless pipes, so we’ll talk about those first.

Anonymous Pipes

Perl’s open function opens a pipe instead of a file when you append or prepend a pipe symbol to the second argument to open. This turns the rest of the arguments into a command, which will be interpreted as a process (or set of processes) that you want to pipe a stream of data either into or out of. Here’s how to start up a child process that you intend to write to:

open SPOOLER, "| cat –v | lpr –h 2>/dev/null"
     || die "can't fork: $!";
 local $SIG{PIPE} = sub { die "spooler pipe broke" };
 print SPOOLER "stuff\n";
 close SPOOLER || die "bad spool: $! $?";

This example actually starts up two processes, the first of which (running cat) we print to directly. The second process (running lpr) then receives the output of the first process. In shell programming, this is often called a pipeline. A pipeline can have as many processes in a row as you like, as long as the ones in the middle know how to behave like filters; that is, they read standard input and write standard output.

Perl uses your default system shell (/bin/sh on Unix) whenever a pipe command contains special characters that the shell cares about. If you’re only starting one command, and you don’t need—or don’t want—to use the shell, you can use the multiargument form of a piped open ...

Get Programming Perl, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.