在 perl 中捕获 shell 退出代码

con*_*ner 0 perl

我正在使用 open 3 使用 perl 执行 shell 命令

   local ( *HANDLE_IN, *HANDLE_OUT, *HANDLE_ERR );

    my $pid = open3( *HANDLE_IN, *HANDLE_OUT, *HANDLE_ERR, @cmd_args ); 
Run Code Online (Sandbox Code Playgroud)

其中@cmd_args = 我的 shell 命令

我的 shell 在退出代码下方返回

0: command executed successfully

>0: error in executing the command
Run Code Online (Sandbox Code Playgroud)

如何在我的 perl 中从 shell 捕获退出代码?

ale*_*oze 5

很简单,看看旧的 perldoc

$pid = open3(\*CHLD_IN, \*CHLD_OUT, \*CHLD_ERR,
    'some cmd and args', 'optarg', ...);

my($wtr, $rdr, $err);
use Symbol 'gensym'; $err = gensym;
$pid = open3($wtr, $rdr, $err,
    'some cmd and args', 'optarg', ...);

waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;
Run Code Online (Sandbox Code Playgroud)

$child_exit_status 然后包含执行的程序的状态。

另一种使用方法是${^CHILD_ERROR_NATIVE}我使用的,特别是在通过反引号执行外部命令时:

my $fancyresult = `ls -lsahR /`;

if (${^CHILD_ERROR_NATIVE} != 0) {
    ...
Run Code Online (Sandbox Code Playgroud)