Can someone please help me? In Perl, what is the difference between:
exec "command";
and
system("command");
and
print `command`;
Are there other ways to run shell commands too?
perl
Can someone please help me? In Perl, what is the difference between:
exec "command";
and
system("command");
and
print `command`;
Are there other ways to run shell commands too?
Best Answer
exec
executes a command and never returns. It's like a
return
statement in 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 returningSTDOUT
,STDERR
or exit status of the command. You can find documentation about it inperlfunc
, because it is a function.system
executes a command and your Perl script is continued after the command has finished.
The return value is the exit status of the command. You can find documentation about it in
perlfunc
.backticks
like
system
executes a command and your perl script is continued after the command has finished.In contrary to
system
the return value isSTDOUT
of the command.qx//
is equivalent to backticks. You can find documentation about it inperlop
, because unlikesystem
andexec
it is an operator.Other ways
What is missing from the above is a way to execute a command asynchronously. That means your perl script and your command run simultaneously. This can be accomplished with
open
. It allows you to readSTDOUT
/STDERR
and write toSTDIN
of your command. It is platform dependent though.There are also several modules which can ease this tasks. There is
IPC::Open2
andIPC::Open3
andIPC::Run
, as well asWin32::Process::Create
if you are on windows.