title: Capturing exit status from STDIN in Perl
body: <p>I have a perl script that is run with a command like this:</p>
  
  <pre><code>/path/to/binary/executable | /path/to/perl/script.pl
  </code></pre>
  
  <p>The script does useful things to the output for the binary file, then exits once STDIN runs out (&lt;> 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, <strong>with a code of 0</strong>.</p>
  
  <p>Is there a way for the perl script to see what the exit code was?  Ideally, I'd want something like this to work:</p>
  
  <pre><code># close STDIN, and if there was an error, exit with that same error.
  unless (close STDIN) {
     print "error closing STDIN: $! ($?)\n";
     exit $?;
  }
  </code></pre>
  
  <p>But unfortunately, this doesn't seem to work:</p>
  
  <pre><code>$ (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
  </code></pre>
  
  <p>Is there a way to have it Do What I Mean?</p>
  
  <p><strong>Edited to add:</strong></p>
  
  <p>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.</p>