develooper Front page | perl.beginners | Postings from March 2002

Re: eval and BEGIN

Thread Previous | Thread Next
Jenda Krynicky
March 15, 2002 17:24
Re: eval and BEGIN
Message ID:
From:           	"James Kelty" <>

> I have looked through the Camel book a couple of times, and I am still
> confused as to the usefullness of the eval, and BEGIN type structures.
> Could someone give me a 'real-world' example, and possibly another
> explanation of the two structures? I would like to know if I should be
> using them in my future code, and what they are REALLY useful for.
> Thanks alot!

Lets begin with BEGIN{}.

Say you'd want to redirect the errors from a script into a log file.
You may of course do this:

	open STDERR, '>my.log';

but this command will be executed AFTER all the "use" 
statements, import() functions in all the used modules and even the 
code "free" code in the modules. Thus if there is a problem this 
early you will not catch it. And if your scrit runs as a daemon or 
service or it doesn't have a console for some reason ... you'll not 
know what  went wrong.

If on the other hand you put that STDERR redirection into a 
BEGIN{} clock on the very top of your script ... you'll catch 

There are of course more examples, but basicaly ... usualy you 
use BEGIN{} blocks if you need to ensure your code runs as soon 
as possible.

For the eval{} blocks:

1. Some modules do not return undef or some other agreed upon 
result if they encounter an error. They just die().

So if you do not put an eval{} block around the module ussage, 
your script will exit and the user will see the error message.

If you put the code into an eval block, you will be able to catch the 
exception, handle it and go on.

2. The exception (error that would otherwise end up being reported 
to the user, but will not thanks to an eval{} block) may be 
generated by a lot of other things.

Imagine you need to compute something and the formula is pretty 
complex. Then for some input values it is not computeable, 
because you divide by zero at one point or other. To find all the 
"forbidden" input values and test them might be tedious.
But your script can't just explode. It should report to the user that 
these input values are wrong and continue.

So you wrap up the computation in an eval{} block, report the errors 
if any and everything is cool.

Basicaly the eval {} block is great if you have to do something 
potentialy dangerous, but cannot let the errors kill the whole script.


=========== == ==========
There is a reason for living. There must be. I've seen it somewhere.
It's just that in the mess on my table ... and in my brain.
I can't find it.
					--- me

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About