Getting the return value of a command executed using backticks in Perl

29,483

Solution 1

You can read the $? variable (as in the shell). From man perlvar

 $?      The status returned by the last pipe close, backtick ("``") command, successful call to wait() or waitpid(), or from the
               system() operator.  This is just the 16-bit status word returned by the traditional Unix wait() system call (or else is made up
               to look like it).  Thus, the exit value of the subprocess is really ("$? >> 8"), and "$? & 127" gives which signal, if any, the
               process died from, and "$? & 128" reports whether there was a core dump.  (Mnemonic: similar to sh and ksh.)

               Additionally, if the "h_errno" variable is supported in C, its value is returned via $? if any "gethost*()" function fails.

               If you have installed a signal handler for "SIGCHLD", the value of $? will usually be wrong outside that handler.

               Inside an "END" subroutine $? contains the value that is going to be given to "exit()".  You can modify $? in an "END"
               subroutine to change the exit status of your program.  For example:

                   END {
                       $? = 1 if $? == 255;  # die would make it 255
                   }

               Under VMS, the pragma "use vmsish 'status'" makes $? reflect the actual VMS exit status, instead of the default emulation of
               POSIX status; see "$?" in perlvms for details.

               Also see "Error Indicators".

Solution 2

And since Perl 5.10, you also have ${^CHILD_ERROR_NATIVE}.

From http://perldoc.perl.org/perl5100delta.html#New-internal-variables :

${^CHILD_ERROR_NATIVE}

This variable gives the native status returned by the last pipe close, backtick command, successful call to wait() or waitpid(), or from the system() operator. See perlvar for details.

Share:
29,483
petersohn
Author by

petersohn

Updated on July 23, 2022

Comments

  • petersohn
    petersohn almost 2 years

    I can do the following in bash:

    output=`command`
    retcode=$?
    

    Is there any way to do the same in Perl? Something like this:

    $output=`command`
    $retcode=???