in reply to Capturing the stdout and exit code from a program piped to perl

One possible way to capture both command output and shell return code is to call the shell a second time. Example of success:
$ perl -E ' @c = `ls f*.*`; $return_code = `echo $?`; say scalar $ret +urn_code;' 0
Example of failure:
$ perl -E ' @c = `ls foobar.*`; $return_code = `echo $?`; say scalar +$return_code;' ls: impossible to find foobar.*: No such file or directory 512
Or something somewhat more similar to what you have:
$ ls *.* | sort | perl -E '@c = <>; say scalar @c, " files"; $return_ +code = `echo $?`; say scalar $return_code;' 294 files 0

Update @ 21:57 UTC: This last syntax does not seem to work properly. It seems that piping the result to the Perl process leads to the loss of the $? value of the initial process (well, or maybe it is more accurate to say that the child process forked by the pipe does not know about the status of the initial process). I get a 0 return code even when the initial command fails:

$ ls foobar.* | perl -E ' $return_code = `echo $?`; say scalar $retu +rn_code;' ls: impossible to find foobar.*: No such file or directory 0
Sorry if this last part of my answer turned out not to be very useful. The first part of my answer still gives you a possible way to go: you can call ./somebinary with back quotes from your Perl script and recover both the output and the return code.

Replies are listed 'Best First'.
Re^2: Capturing the stdout and exit code from a program piped to perl
by Anonymous Monk on Dec 11, 2014 at 11:48 UTC
    Laurent_R, on what kind of system did you try the ls | perl command? I ask for impossible to find in ls error message is new to me (have not seen yet on FreeBSD 4.x to 8.4-STABLE, Redhat CentOS 5, 6).
      Hi, I tried it on Cygwin (linux/bash emulator under Windows) and AIX (IBM's brand of Unix). This is the message under AIX:
      ls foobar.* | perl -E ' $return_code = `echo $?`; say scalar $return +_code;' ls: cannot access foobar.*: A file or directory in the path name does +not exist. 0
      Well, now that I think about it, I translated into English the original message, to make it clearer to the English-speaking reader.