O'Reilly logo

Learning Perl, Second Edition by Randal L. Schwartz, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required