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.[87] 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:

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

Get Learning Perl on Win32 Systems 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.