Sadhun
Sadhun

Reputation: 264

Return status of perl script

I came across the following script,

$num=53535.35353535;

$result1=printf("Result = %.2f\n",$num);
print "$result1 \n";
print $?;   # prints the return status

Output of the script is,

53535.35
1
0

I see return status of print is stored in $result1 which is 1. Since print executed fine it is success and its true condition is displayed as 1. Whereas the return status of the script is in $? which is 0.

Is both 1 and 0 true in this script? please correct me if am wrong.

Upvotes: 0

Views: 858

Answers (1)

SzG
SzG

Reputation: 12609

Perldoc does not specify the return value of printf, so it's pointless to capture and evaluate it. It seems to be 1, whatever you do.

As to $?, it shows the exit status of the last external program you ran via system or backticks, etc. You don't run any external program, so it's meaningless too.

BTW, you have to be careful with exit statuses, because 0 means success, anything else is error. system also returns the exit status of the external program, and you might be tempted to do this:

system "someprogram" or print "Error in someprogram\n";

This is wrong, as 0 means success, but Perl treats zero as false. Instead it should be:

system "someprogram" and print "Error in someprogram\n";

which is kind of counter-intuitive and difficult to read. So it's even better to do this:

print "Error in someprogram\n" if system "someprogram" != 0;

Upvotes: 2

Related Questions