Propagating Perl exit code

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");
print STDERR "Child script failed!\n" if ($result != 0);

my $exit_value = system($command);

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;

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);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s