#-- calling 'command' with arguments
system("command arg1 arg2 arg3");
#-- better way of calling the same command
system("command", "arg1", "arg2", "arg3");
The return value is set in
$?
; this value is the exit status of the command as returned by the 'wait' call; to get the real exit status of the command you have to shift right by 8 the value of $? ($? >> 8).
If the value of
$?
is -1, then the command failed to execute, in that case you may check the value of
$!
for the reason of the failure.
Example:
system("command", "arg1");
if ( $? == -1 )
print "command failed: $!\n";
else{
printf "command exited with value %d", $? >> 8;
-
- Using exec()
-
The exec() function executes the command specified and never returns to the calling program, except in the case of failure because the specified command does not exist AND the exec argument is an array.
Like in system(), is recommended to pass the arguments of the functions as an array.
-
- Using backticks (``)
-
In this case the command to be executed is surrounded by backticks. The command is executed and the output of the command is returned to the calling script.
In scalar context it returns a single (possibly multiline) string, in list context it returns a list of lines or an empty list if the command failed.
The exit status of the executed command is stored in $? (see system() above for details).
Example:
#-- scalar context
$result = `command arg1 arg2`;
#-- the same command in list context
@result = `command arg2 arg2`;
Notice that the only output captured is STDOUT, to collect messages sent to STDERR you should redirect STDERR to STDOUT
Example:
#-- capture STDERR as well as STDOUT
$result = `command 2>&1`;
-
- Using open()
-
Use open() when you want to:
- capture the data of a command (syntax: open("command |"))
- feed an external command with data generated from the Perl script (syntax: open("| command"))
Examples:
#-- list the processes running on your system
open(PS,"ps -e -o pid,stime,args |") || die "Failed: $!\n";
while ( )
#-- do something here
#-- send an email to user@localhost
open(MAIL, "| /bin/mailx -s test user\@localhost ") || die "mailx failed: $!\n";
print MAIL "This is a test message";
There are many ways to execute external commands from Perl. The most commons are:system functionexec functionbackticks (``) operatoropen functionAll of these methods have different behaviour, so