ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы.



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 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.[2] Here's an example of creating a filehandle out of a netstat process. Because the process is generating output that we want to read, we make a filehandle that is open for reading, like so:

[2] But not both at once. See Chapter 6 of Programming Perl for examples of bidirectional communication.

open(NETPROC, "netstat|"); # open netstat for reading

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

@netstat = <NETPROC>;

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(FIND,"|find $pattern");
print FIND @filedata;
close(FIND);

In this case, after opening FIND, we wrote some data to it and then closed it. Opening a process with a process filehandle allows the command to execute in parallel with the Perl program. Saying close on the filehandle forces the Perl program to wait until the process exits. If you don't close the filehandle, the process can continue to run even beyond the execution of the Perl program.

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 a dir process, which pipes its output into a sort process, which finally sends its output along to the DIRPR filehandle:

open(DIRPR, "dir | sort |");

The exit function causes an immediate exit from the current Perl process. You'd use this to abort a Perl program from somewhere in the middle. The exit function takes an optional parameter, which serves as the numeric exit value that can be noticed by the parent process. The default is to exit with a zero value, indicating that everything went OK.