exec LIST
This function terminates the currently running Perl script by
executing another program in place of itself. If there is more than
one argument in LIST
(or if LIST
is an array with more than one value)
the function calls C's execvp(3) routine with the arguments in
LIST
. This bypasses any shell processing of the command.
If there is only one scalar argument, the argument is checked
for shell metacharacters. If metacharacters are found, the entire argument is
passed to "/bin/sh -c
" for parsing.[3]
If there are no metacharacters, the argument is split into words and passed
directly to execvp(3) in the interests of efficiency, since
this bypasses all the overhead of shell processing.
Ordinarily exec never returns - if it does return, it always
returns false, and you should check $! to find out what went
wrong.
Note that exec (and system) do not flush your output
buffer, so you may need to enable command buffering by setting
$| on one or more filehandles to avoid lost output.
This statement runs the echo program to print the current argument list:
[3] Under UNIX, that is. Other operating systems may use other command interpreters.
exec 'echo', 'Your arguments are: ', @ARGV;
This example shows that you can exec a pipeline:
exec "sort $outfile | uniq" or die "Can't do sort/uniq: $!\n";
The UNIX execv(3) call provides the ability to tell a
program the name it was invoked as. This name might have nothing to
do with the name of the program you actually gave the operating system
to run. By default, Perl simply replicates the first element of LIST
and uses it for both purposes. If, however, you don't really want to
execute the first argument of LIST
, but you want to lie to the program
you are executing about its own name, you can do so.
Put the real name of the program
you want to run into a variable and
then put that variable out in front of the LIST
without a comma,
kind of like a filehandle for a print statement. (This always
forces interpretation of the LIST
as a multi-valued list, even if
there is only a single scalar in the list.) Then the first element of
LIST
will be used only to mislead the executing program as to its
name. For example:
$shell = '/bin/csh'; exec $shell '-sh', @args; # pretend it's a login shell die "Couldn't execute csh: $!\n";
You can also replace the simple scalar holding the program name with a block containing arbitrary code, which simplifies the above example to:
exec {'/bin/csh'} '-sh', @args; # pretend it's a login shell