tags:

views:

120

answers:

3

I am using syntax checking to see whether my Perl script is being used in the correct way. If the syntax is not correct, I display a message saying what the correct syntax is and then end the execution of the program.

Out of

print "Please use the following syntax: ...";
exit 1;

and

die("Please use the following syntax: ...");

which one should I use? I know die would have been the answer if exception handling was in place. But that is not the case.

Which one is the better choice for program termination without exception handling? Please say why also.

+5  A: 

print prints to STDOUT but die prints to STDERR

exit 1 exits with exit status of 1 but die exits with exit current value of errno that is $!

Hence die is the preferred way as its simpler and shorter.

codaddict
or `$? >> 8` if `$!` is `0`. or 255 if `$? >> 8` is 0.
Chas. Owens
@codaddict, @Chas: What are `$!`, `$?`?
Lazer
[$OS_ERROR](http://p3rl.org/var#%24OS_ERROR), [$CHILD_ERROR](http://p3rl.org/var#%24CHILD_ERROR)
daxim
@codaddict `$!` is a special variable that exposes the C errno value. `$?` a special variable that holds information about the last program executed by `system`, backticks, etc. See http://perldoc.perl.org/perlvar.html#%24ERRNO and http://perldoc.perl.org/perlvar.html#%24CHILD_ERROR for more information.
Chas. Owens
+7  A: 

It depends on what you want to have happen with STDERR and STDOUT. I prefer to send error and warning type messages to STDERR so that when someone is trying to redirect output to a file they still see the error messages; However, there are times though when STDOUT is used to communicate status to the user so he or she can tail -f or paginate it, and at those times writing to STDERR causes them pain (they have to redirect STDERR back into STDOUT with 2>&1, and not everyone knows how to do that). So which to use, die or print and exit, depends heavily one which type or program you are writing.

There are other benefits/drawbacks to using die:

  • You can trap die with an eval, but not exit
  • You can run code when the program calls die by installing a signal handler for the __DIE__ signal
  • You can easily override the die function

Each of those has times where it is handy to be able to do them, and times when it is a pain that they can be done.

Chas. Owens
+3  A: 

It is best to follow existing practice ("rule of least surprise"): exit with 2 on a fatal error such as a syntax error.

daxim