Ïðèãëàøàåì ïîñåòèòü
Ðåëèãèÿ (religion.niv.ru)

The system() Function

Previous Table of Contents Next

The system() Function

The simplest way to run a command outside Perl is to use the system function. The system function pauses the Perl program, runs the external command, and then continues running your Perl program. The syntax for system is


system command;


where command is the command that you want run. The return value from system is 0 if everything goes okay or nonzero if a problem occurs. Notice that this result is backward from the normal Perl values of true and false.

The following is an example of system under Unix:


system("ls -lF");        # Print a file listing

# print system's documentation

if ( system("perldoc -f system") ) {

    print "Your documentation isn't installed correctly!\n";

}


This next example shows system under MS-DOS/Windows:


system("dir /w");        # Print a file listing

# print system's documentation

if ( system("perldoc -f system") ) {

    print "Your documentation isn't installed correctly!\n";

}


For the most part, system works the same under both architectures. The point to remember is that the commands are fundamentally different from one OS to another. To get a file listing in MS-DOS, you use the dir command; to get a file listing under Unix, you use the ls command. In very rare instances—perldoc, for example—the commands are similar under Unix and MS-DOS.

When the system function is running the external command, the output of that command is displayed on your screen as though your Perl program were printing it. If that external command needs input, the input comes from your terminal the same way your Perl programs read input from the terminal. The command run by system inherits the STDIN and STDOUT file descriptors, so the external command does I/O from the exact same place as your Perl program. Invoking fully interactive programs from system is possible.

Consider the following example under Unix:


$file="myfile.txt";

system("vi $file");


Now consider this example under Windows/MS-DOS:


$file="myfile.txt";

system("edit $file");


Each of the preceding examples runs an editor on myfile.txt—vi for Unix and edit for DOS. The editor runs full screen, of course, and all the normal editor commands work. When the editor exits, control returns to Perl.

You can use the system function to run any program, not just console-mode programs (text). Under Unix, this example runs a graphical clock:


system("xclock -update 1");


Under MS-DOS/Windows, the following example invokes a graphical file editor:


system("notepad.exe myfile.txt");


Previous Table of Contents Next