Hmm. I think what your saying is that the eval is necessary to avoid a warning if $var doesn't contain a value for which there is a label defined?
If so, then it still doesn't handle the case where $var is undefined.
That can be handled by using a do BLOCK construct to disable warnings and adding a CASE0:
for my $var ( undef, 1 .. 10, 'fred' ) {
goto 'CASE' . do{ local $^W; $var + 0 };
CASE10: print "a";
CASE9: print "b";
CASE8: print "c";
CASE7: print "d";
CASE6: print "e";
CASE5: print "f";
CASE4: print "g";
CASE3: print "h";
CASE2: print "i";
CASE1: print "j";
print "\n";
CASE0:
}
I sort of wonder why this isn't given as one of the ways of achieving C-like switch statement behavior in the perl docs? Oh, well... it's probably horribly inefficient or something (apart from just being to C-ish or something).
C-ish it may be (though that's not a good reason in my book if it is clearer), but inefficient it is not:
P:\test>388915
?> 1..10
Testing for vals [1..10]
Rate if_cascade and_cascade goto_do goto_eval
+ goto
if_cascade 11395/s -- -2% -11% -26%
+ -26%
and_cascade 11627/s 2% -- -9% -24%
+ -25%
goto_do 12845/s 13% 10% -- -17%
+ -17%
goto_eval 15389/s 35% 32% 20% --
+ -0%
goto 15423/s 35% 33% 20% 0%
+ --
?>
Benchmark/results
Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail
"Memory, processor, disk in that order on the hardware side. Algorithm, algorithm, algorithm on the code side." - tachyon
|