next up previous contents
Next: Environmental Variables Up: Interacting with the Operating Previous: The stat function   Contents

The system function

When you wish to execute an operating system command, but don't care about capturing the output, you can provide the command as an argument to the system function. The command will be executed just as if you typed it into a shell on your computer. When you use system, the input to the command you're executing (if any) comes from the same input stream as your perl program reads from; similarly, the output of the command (if any) goes to the same output stream as your perl program.

The return value of the system command is the exit status of the command from your operating system's shell. Since shells tend to return a value of zero to indicate success, and non-zero values which indicate the nature of an error, you'll need to reverse the usual logic of checking for errors from calls to the system function. Suppose we have written a perl program which produces a C program, and we wish to compile that program from inside of perl. We can invoke a system call to the C compiler (cc or gcc on UNIX systems) through the system function, but we need to report an error if the function returns a non-zero value. Thus, a check like the following could be done:

system("cc $program") && print("Error compiling $program\n");
The && operator will be short-circuited if the call to system returned a zero (success), so the error message only prints when system returns a non-zero value.

Try to avoid the temptation of calling system to perform all operating system tasks, simply because you know how to do those tasks through a shell command. Many times, perl has internal equivalents to these shell commands which are more efficient. (See Section [*].)


next up previous contents
Next: Environmental Variables Up: Interacting with the Operating Previous: The stat function   Contents
Phil Spector 2002-10-18