14.3 Using Processes as FilehandlesYet 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
Note the
vertical bar on the right side of @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, after opening Opening a process for writing causes the command's standard input to come from the filehandle. The process shares the standard output and standard error with Perl. As before, you may use /bin/sh -style I/O redirection, so here's one way to simply discard the error messages from the lpr command in that last example: open(LPR,"|lpr -Pslatewriter >/dev/null 2>&1");
The You could even combine all this, generating a report of everyone except Fred in the list of logged-on entries, like so: open (WHO,"who|"); open (LPR,"|lpr -Pslatewriter"); while (<WHO>) { unless (/fred/) { # don't show fred print LPR $_; } } close WHO; close LPR;
As this code fragment reads from the
You don't have to open just one command at a time. You can open an entire pipeline. For example, the following line starts up an
ls
(1) process, which pipes its output into a
tail
(1) process, which finally sends its output along to the open(WHOPR, "ls | tail -r |"); |
|