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, then possibly grabs its output. But Perl can also launch a child process that stays alive, communicating[†] 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 either 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 is now launched and
continues independently of the Perl process.[‡] The open fails if the child process cannot be created. If the command itself does not 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. ...
Get Learning Perl, 5th 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.