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.
Between:
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 also say why.
exit() function evaluates the expression passed to it and exits from the Perl interpreter while returning the value as the exit value. The exit() function does not always exit immediately but calls the end routines before it terminates the program.
Re: How can I stop a running perl script? In the ssh window where it is running you can often just hit ctrl+c to kill it however there are some instances where that will not work. The kill command would be the next step.
The die() function can be used to stop the script and can be used to display a message to the end user. It can be used at the right side of the OR ( || ) operator and at left side can be any expression like the eval() function.
To exit from a subroutine, pass on or return is utilized. Where, The value of the function is returned only when it is called for it. It returns the value which is passed in the beginning, or it returns a 0 if no value is passed.
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 on what type of program you are writing.
There are other benefits/drawbacks to using die
:
die
with an eval
, but not exitdie
by installing a signal handler for the __DIE__
signaldie
functionEach 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With