O'Reilly logo

Perl Cookbook by Nathan Torkington, 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

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

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