Tip: prevent “die” from writing the script name and line number

Normally when you use “die” with a message in perl, the result looks like this:

Can't open registry key Software\MyCompany\MyKey at MyScript.pl line 112

So, next time, just add ‘\n’ to the die message, and you’ll get

Can't open registry key Software\MyCompany\MyKey

Strange… but works!

Advertisements

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.

parent.pl:

my $result = system("perl child.pl");
print STDERR "Child script failed!\n" if ($result != 0);

child.pl:

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