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:
system "xv $imagename";
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
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:
$pid=open READER, "programname arguments|" or die "Can't run the progr
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.
$pid=open WRITETOME, "|programname arguments" or die "Couldn't fork pr
print WRITETOME "write this\n";
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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
Outside of code tags, you may need to use entities for some characters:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
| & || & |
| < || < |
| > || > |
| [ || [ |
| ] || ] |