I have a Perl script which calls another Perl script. The ‘child’ script returns the exit code of a system command and the ‘parent’ script should check it and act accordingly.
my $result = system("perl child.pl"); print STDERR "Child script failed!\n" if ($result != 0);
my $exit_value = system($command); exit($exit_value);
However, even if the system command fails, the parent script always receives “success”.
I finally discovered that Perl only considers the lower 8 bits of the exit() argument. Hence exit codes like 256 or 512 (which are quite common in operating system commands) are interpreted as 0.
I have two solutions for this problem:
1. If you need the exact exit code, Shift-right the exit code of the system command, then return the result.
my $result = system($command); my $exit_value = $result >> 8; exit($exit_value);
2. if you just need to know if the child command was successful, you can use “die” instead of “exit” in case the system command fails.
my $result = system($command); die if ($result != 0);