Running Another Program
Problem
You want to run another program from your own, pause until the other program is done, and then continue. The other program should have same STDIN and STDOUT as you have.
Solution
Call system
with a string to have the shell interpret the string as a command
line:
$status = system("vi $myfile");
If you don’t want the shell involved, pass
system
a list:
$status = system("vi", $myfile);
Discussion
The system
function is the simplest and most
generic way to run another program in Perl. It doesn’t gather
the program’s STDOUT like backticks or open
.
Instead, its return value is (essentially) that program’s exit
status. While the new program is running, your main program is
suspended, so the new program can read from your STDIN and write to
your STDOUT so users can interact with it.
Like open
, exec
, and backticks,
system
uses the shell to start the program
whenever it’s called with one argument. This is convenient when
you want to do redirection or other tricks:
system("cmd1 args | cmd2 | cmd3 >outfile"); system("cmd args <infile >outfile 2>errfile");
To avoid the shell, call system
with a list of
arguments:
$status = system($program, $arg1, $arg); die "$program exited funny: $?" unless $status == 0;
The returned status value is not just the exit value: it includes the
signal number (if any) that the process died from. This is the same
value that wait
sets $?
to. See
Section 16.19 to learn how to decode this value.
The system
function (but not backticks) ignores SIGINT ...
Get Perl Cookbook 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.