title: Perl: Capturing correct return value from 'system' command
body: <p>I'm a beginner in Perl. I have a Windows batch script which contains multiple NMake commands. An existing issue with this batch script is that even if the NMake command fails during its execution, <code>ERRORLEVEL</code> doesn't get set properly.</p>
  
  <p>So we never know whether the command worked until we parse the log file. I looked into it but couldn't find a solution. I, then thought of converting this batch script to a Perl script assuming that trapping error will be easier but it seems it's not that easy :) </p>
  
  <p>Whenever I run my Perl script, the 'system' command always returns 0. I looked at many different links, and realized that capturing the correct return status of 'system' command is not that straightforward. Still, I tried the suggestions but things are not working. :(</p>
  
  <p>Let me mention that the NMake command that is called, in turn, calls many different commands during its execution. For instance, the command output mentioned below, which is throwing 'fatal error', is actually part of a Perl script (check_dir.pl). This call to Perl script is written in the NMake file itself.</p>
  
  <p>If I call this Perl file (<code>check_dir.pl</code>) <em>directly</em> and check for exit value, I get correct result i.e., the command fails and prints a <em>non-zero</em> exit value (...<em>unexpectedly returned exit value 2</em>). </p>
  
  <p>Tried Perl's system function but it didn't help. I used the following code:</p>
  
  <pre><code>system ("nmake /f _nt.mak pack_cd SUB_PLAT=$PLAT DR=$plat 2&gt;&amp;1");
  
  if ( $? == -1 ) {
      print "Command failed to execute: $!\n";
  }
  elsif ( $? &amp; 127 ) {
      printf "The child died with signal %d, %s a coredump\n",
      ( $? &amp; 127 ), ( $? &amp; 128 ) ? 'with' : 'without';
  }
  else {
      printf "child exited with value %d\n", $? &gt;&gt; 8;
  }
  </code></pre>
  
  <p>Output:  </p>
  
  <pre>.....  
  .....  
  Unable to open dir: R:\TSM_Latest  
  Compressing...NMAKE : fatal error U1077: 'if' : return code '0x2'  
  Stop.  
  child exited with value 0</pre>
  
  <p>Also tried:  </p>
  
  <pre><code>use IPC::System::Simple qw(system);  
  my $exit_status = system ("nmake /f _nt.mak pack_cd SUB_PLAT=$PLAT DR=$plat 2&gt;&amp;1");
  
  if ($exit_status != 0) {  
      print "Failure";  
      exit 3;  
  } else {  
      print "Success";  
  }
  </code></pre>
  
  <p>Finally tried the following module: </p>
  
  <pre><code>use IPC::Run qw( run timeout );  
  run "nmake /f _nt.mak pack_cd SUB_PLAT=$PLAT DR=$plat 2&gt;&amp;1" or die "NMake returned $?";
  </code></pre>
  
  <p>Nothing seems to be working :(</p>
  
  <p>Please correct me if i'm interpreting the return value of <code>system</code> incorrectly.</p>