in reply to while loop question

What about using eval { ... } around the loop and die instead of last?
eval { while(CONDITION) { die if SOMETHING; die if SOMETHING_ELSE; ... } }; if(not $EVAL_ERROR) { # loop finished on it's own accord }
About as quickly as I thought of this, I remembered a best practice that says something like "do not use exceptions for control flow". I was about to retract my suggesttion, but figured I would ask the other monks. Is the consensus among the monks that using eval/die like this is bad? I suppose it depends on the true nature of the SOMETHING and SOMETHING_ELSE cases.

Replies are listed 'Best First'.
Re^2: while loop question
by Athanasius (Archbishop) on Sep 06, 2012 at 16:01 UTC

    I can think of two reasons to not use die/eval for (normal) control flow:

    (1) Clarity. An exception is supposed to indicate — well, an exceptional condition: either an error, or a resource failure. Throwing an exception as a part of normal execution is liable to mislead maintainers of the code when they try to understand what’s going on. So, at the very least, it’s poor style.

    (2) Efficiency. Consider the following code:

    #! perl use strict; use warnings; use Benchmark qw(cmpthese); cmpthese(1_000_000, { 'bare_loop' => \&bare_loop, 'eval_loop' => \&eval_loop, }); sub bare_loop { my ($count, $evens, $flag) = (100, 0, 0); while ($count--) { next if $count % 2; # odd if ($count == 50) { $flag = 1; last; } ++$evens; } print "Normal loop exit\n" unless $flag; } sub eval_loop { my ($count, $evens) = (100, 0); eval { while ($count--) { next if $count % 2; # odd die if $count == 50; ++$evens; } }; print "Normal loop exit\n" unless $@; }

    Typical output (on my machine):

    Rate eval_loop bare_loop eval_loop 71541/s -- -23% bare_loop 92362/s 29% --

    So, there is a definite performance penalty for throwing and then catching the exception. Not nearly as great a penalty as in a language like C++, but still — why opt for a less efficient method when the more efficient methods are just as easy to use?

    Athanasius <°(((><contra mundum