Can someone please help me? In Perl, what is the difference between:
exec \"command\";
and
system(\"command\");
What's the difference between Perl's backticks (`
), system
, and exec
?
exec -> exec "command"; ,
system -> system("command"); and
backticks -> print `command`;
exec
exec
executes a command and never resumes the Perl script. It's to a script like a return
statement is to a function.
If the command is not found, exec
returns false. It never returns true, because if the command is found, it never returns at all. There is also no point in returning STDOUT
, STDERR
or exit status of the command. You can find documentation about it in perlfunc, because it is a function.
E.g.:
#!/usr/bin/perl
print "Need to start exec command";
my $data2 = exec('ls');
print "Now END exec command";
print "Hello $data2\n\n";
In above code, there are three print
statements, but due to exec
leaving the script, only the first print statement is executed. Also, the exec
command output is not being assigned to any variable.
Here, only you're only getting the output of the first print
statement and of executing the ls
command on standard out.
system
system
executes a command and your Perl script is resumed after the command has finished. The return value is the exit status of the command. You can find documentation about it in perlfunc.
E.g.:
#!/usr/bin/perl
print "Need to start system command";
my $data2 = system('ls');
print "Now END system command";
print "Hello $data2\n\n";
In above code, there are three print
statements. As the script is resumed after the system
command, all three print statements are executed.
Also, the result of running system
is assigned to data2
, but the assigned value is 0
(the exit code from ls
).
Here, you're getting the output of the first print
statement, then that of the ls
command, followed by the outputs of the final two print
statements on standard out.
`
)Like system
, enclosing a command in backticks executes that command and your Perl script is resumed after the command has finished. In contrast to system
, the return value is STDOUT
of the command. qx//
is equivalent to backticks. You can find documentation about it in perlop, because unlike system and exec
, it is an operator.
E.g.:
#!/usr/bin/perl
print "Need to start backticks command";
my $data2 = `ls`;
print "Now END system command";
print "Hello $data2\n\n";
In above code, there are three print
statements and all three are being executed. The output of ls
is not going to standard out directly, but assigned to the variable data2
and then printed by the final print statement.