O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required