I have a perl script that is run with a command like this:
/path/to/binary/executable | /path/to/perl/script.pl
The script does useful things to the output for the binary file, then exits once STDIN runs out (<> returns undef). This is all well and good, except if the binary exits with a non-zero code. From the script's POV, it thinks the script just ended cleanly, and so it cleans up, and exits, with a code of 0.
Is there a way for the perl script to see what the exit code was? Ideally, I'd want something like this to work:
# close STDIN, and if there was an error, exit with that same error.
unless (close STDIN) {
print "error closing STDIN: $! ($?)\n";
exit $?;
}
But unfortunately, this doesn't seem to work:
$ (date; sleep 3; date; exit 1) | /path/to/perl/script.pl /tmp/test.out
Mon Jun 7 14:43:49 PDT 2010
Mon Jun 7 14:43:52 PDT 2010
$ echo $?
0
Is there a way to have it Do What I Mean?
Edited to add:
The perl script is manipulating the output of the binary command in real-time, so buffering it all into a file is not a feasible solution. It doesn't, however, need to know the exit code until the end of the script.