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

Re[2]: eval and BEGIN

Thread Previous
Daniel Gardner
March 16, 2002 13:24
Re[2]: eval and BEGIN
Message ID:
Saturday, March 16, 2002, 1:24:11 AM, Jenda Krynicky wrote:
> 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.

Here's a very simplified example of what Jenda means:

   #!/usr/bin/perl -w

   use strict;

   my $result;
   eval {
      $result = div_by(0);
   if ($@) {
      if ($@ =~ /division by zero/) {
         $result = "undefined due to division by zero";
      } else {
         die $@;

   print "result is: $result\n";

   sub div_by {
      my $value = shift;
      return 10 / $value

We have a function "div_by", which returns 10 divided by
it's input. Obviously if we passed the value zero to this
function, it will die.

We can wrap the call to the dangerous function in an eval
block, which means we can test to see if the code did in
fact die(), and what the error message was. The error will
be held in a special variable $@ (mnemonic "Where the error
was at").

In this case it would probably be easier to check the input
values for zero, but the eval/die method is perfectly valid.

Best Regards,

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