in reply to How to catch the return code of another program?

Use system instead of backticks:

my $output = system($exec); print ($output >> 8), "\n";

Update: If you need to capture the output as well as the return value of the external application, use Capture::Tiny. See the recent thread Problem logging STDOUT in perl.

Hope that helps,

Athanasius <°(((><contra mundum

Replies are listed 'Best First'.
Re^2: How to catch the return code of another program?
by hary536 (Novice) on Aug 29, 2012 at 01:15 UTC
    Hi, Thanks for replying. Two questions and also, I think I may have missed some detail in my question. (1) When I tried your above code, it always prints 255. (2) What does >> 8 do? I searched online and was led to the "die"explanation, but couldn't find what >>8 means. Now, the detail I missed in my initial question was that: My code is like below: $output = "Folder/OtherTool arguments_to_the_other_tool. " I had earlier mentioned only "Folder/OtherTool", so just clarifying here.

      Hello hary536,

      The following little scripts will help you to see what’s going on. Put them in the same directory:

      #! perl # File: application.pl use strict; use warnings; my $code = $ARGV[0] // 0; printf "In application: result = '%5d' (decimal) or '%016b' (binary)\n +", $code, $code; exit $code;
      #! perl # File: driver.pl use strict; use warnings; my $code = $ARGV[0] // 0; my @app = ('perl', 'application.pl', $code); my $result = system(@app); printf "In driver: result = '%5d' (decimal) or '%016b' (binary)\n +", $result, $result; printf " >> 8 = '%5d' (decimal) or '%016b' (binary)\n +", ($result >> 8), ($result >> 8);

      Now, if you run, say,

      perl driver.pl 255

      from the command line, you should see this output:

      In application: result = ' 255' (decimal) or '0000000011111111' (bina +ry) In driver: result = '65280' (decimal) or '1111111100000000' (bina +ry) >> 8 = ' 255' (decimal) or '0000000011111111' (bina +ry)

      which shows that the return value from the application called via system has been left-shifted by 8 binary digits (i.e., multiplied by 256). See the Perl documentation entry for system, and also the explanation by Perlbotics in the recent post Re: getting the bash exit code.

      Note that command line arguments are fed to system as a list, in this case supplied by the array @app in this line of driver.pl:

      my $result = system(@app);
      When I tried your above code, it always prints 255

      The application is returning -1, which usually indicates failure. What happens when you run the application directly from the command line?

      Hope that helps,

      Athanasius <°(((><contra mundum