Processes as Filehandles

So far, we’ve been looking at ways to deal with synchronous processes, where Perl stays in charge, launches a command, (usually) waits for it to finish, and possibly grabs its output. But Perl can also launch a child process that stays alive, communicating[327] to Perl on an ongoing basis until the task is complete.

The syntax for launching a concurrent (parallel) child process is to put the command as the “filename” for an open call and to precede or follow the command with a vertical bar, which is the “pipe” character. For that reason, this is often called a piped open:

    open DATE, "date|" or die "cannot pipe from date: $!";
    open MAIL, "|mail merlyn" or die "cannot pipe to mail: $!";

In the first example, with the vertical bar on the right, the command is launched with its standard output connected to the DATE filehandle opened for reading, similar to the way that the command date | your_program would work from the shell. In the second example, with the vertical bar on the left, the command’s standard input is connected to the MAIL filehandle opened for writing, similar to what happens with the command your_program | mail merlyn. In either case, the command launches and continues independently of the Perl process.[328] The open fails if the child process cannot be created. If the command doesn’t exist or exits erroneously, this will (generally) not be seen as an error when opening but as an error when closing. We’ll get to that in a moment.

For all intents ...

Get Learning Perl, Fourth Edition 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.