Reading or Writing to Another Program

Problem

You want to run another program and either read its output or supply the program with input.

Solution

Use open with a pipe symbol at the beginning or end. To read from a program, put the pipe symbol at the end:

$pid = open(README, "program arguments |")  or die "Couldn't fork: $!\n";
while (<README>) {
    # ...
}
close(README)                               or die "Couldn't close: $!\n";

To write to the program, put the pipe at the beginning:

$pid = open(WRITEME, "| program arguments") or die "Couldn't fork: $!\n";
print WRITEME "data\n";
close(WRITEME)                              or die "Couldn't close: $!\n";

Discussion

In the case of reading, this is similar to using backticks, except you have a process ID and a filehandle. As with the backticks, open uses the shell if it sees shell-special characters in its argument, but it doesn’t if there aren’t any. This is usually a welcome convenience, because it lets the shell do filename wildcard expansion and I/O redirection, saving you the trouble.

However, sometimes this isn’t desirable. Piped opens that include unchecked user data would be unsafe while running in taint mode or in untrustworthy situations. Section 19.6 shows how to get the effect of a piped open without risking using the shell.

Notice how we specifically call close on the filehandle. When you use open to connect a filehandle to a child process, Perl remembers this and automatically waits for the child when you close the filehandle. If the child hasn’t exited by then, Perl waits until it ...

Get Perl Cookbook 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.