|Syntactic Confectionery Delight|
Working with other processes and programsby vroom (Pope)
|on Jan 04, 2000 at 23:31 UTC||Need Help??|
Perl makes it very easy to interface between other programs. In this tutorial you'll learn how to do some very basic things like writing to another program, reading the output from another program, just running an outside program.
The easiest and most often used way to run a program is to use the system function. When system is called a child process is made and executed, once it is finished it returns to the parent program (your script) and continues with its execution.
For example if you had an image processing script you might want to allow a user to view the resulting image at some point. You could do this with a call like the following:
When the system call was made in the program it would launch the program in this case xv. The execution of our program would stop until after we had closed our xv program. After we close xv however our Perl script would continue to run the code after the system statement.
Now lets say you want to collect the output from a program and do something to it. There are at least two ways to do this. One is with backticks (usually on the key to the left of your 1 key). This allows you to collect all of the output from a program into a variable;
Another way is to use open with a pipe. Basically this works the same as working with a filehandle that you're reading from. All you do is something like:
This open call returns the process id of the process it spawns. Then you just read from the handle with the <> operator and close it when you're finished. If you think about how you write to files you can probably guess how you write to processes.
All you have to do is open the process with the pipe on the left side, and then handle it like you would handle printing to a file.
If you want to read and write to the same process take a look at IPC::Open2 if you want to handle stderr in addition to that check out IPC::Open3