14.3. Using Processes as Filehandles

Yet another way to launch a process is to create a process that looks like a filehandle (similar to the popen (3) C library routine if you're familiar with that). We can create a process-filehandle that either captures the output from or provides input to the process.[4] Here's an example of creating a filehandle out of a who(1) process. Because the process is generating output that we want to read, we make a filehandle that is open for reading, like so:

open(WHOPROC, "who|"); # open who for reading

[4] But not both at once. See Chapter 6 of Programming Perl or perlipc (1) for examples of bidirectional communication.

Note the vertical bar on the right side of who. That bar tells Perl that this open is not about a filename, but rather a command to be started. Because the bar is on the right of the command, the filehandle is opened for reading, meaning that the standard output of who is going to be captured. (The standard input and standard error remain shared with the Perl process.) To the rest of the program, the WHOPROC handle is merely a filehandle that is open for reading, meaning that all normal file I/O operators apply. Here's a way to read data from the who command into an array:

@whosaid = <WHOPROC>;

Similarly, to open a command that expects input, we can open a process-filehandle for writing by putting the vertical bar on the left of the command, like so:

open(LPR,"|lpr -Pslatewriter");
print LPR @rockreport;
close(LPR);

In this case, ...

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.