in reply to return eval { die() } idiom

I use it sometimes. It is really just a try/catch/throw. I normally use so I don't have to check the return value of a whole bunch of functions. For example:
eval{ ##Do DB Stuff if($db->Sql($sql)){ die "Error Querying SQL. Error: " . $db->Error(); } ... ## Send email my $sender = new Mail::Sender({smtp => $smtp, on_errors => 'die'})|| die "Failed Mail::Sender object creation: $Mail::Sender +::Error\n"; ## Do more Mail::Sender stuff, which will die on failure ##because of on_errors => 'die' ... }; &write_error_log($@) if($@);

Replies are listed 'Best First'.
Re: Re: return eval { die() } idiom
by lestrrat (Deacon) on Aug 29, 2003 at 19:42 UTC

    thanks, but that I understand:

    eval { # blah blah... die ("fooblah"); # or something_that_may_die(); }; if($@) { # do something }

    That's how I would normally use it.

    I'm talking about this: "return eval { BLOCK }", where BLOCK is the main block of your code...

      Dear lestrrat
      AFAIK, the only difference between tfc22's code and yours is the way you handle errors. In essense, both codes do the same thing. I really see no point about where you die() for errors, since you die() for errors somewhere in your code.
      What I see is Just Another Way To Do It.
      Maybe some benchmarking could reveal something more interesting.

      On the other hand, as you mentioned before, the guys who coded the initial snippet use to code C, and the idiom is much more readable to C programmers than it is for smalltalk-based perl programmers (like me). Maybe this is the advantage you're looking for: C programmers that see this kind of construction will more likely recognise it (and feel at home) than programmers with other backgrounds.

      My two pence.

      =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
      monsieur_champs

      I personally don't really like that construct, but I have seen it used. I really think that it is just a matter of preference. Using the return eval construct, makes you function behave more like a built-in function, returning a status and setting an error variable($@) if needed. This can be done many other ways as I'm sure you are aware(TIMTOWTDI).

      I haven't ran Benchmark, so I'm not sure, but this seems like it would be slower than just checking the return status, setting an error variable, then returning.