I would like to use a simple Switch/Case setup for processing discontinuous numerical values and/or string error codes. I have read through the posts/faq that I could find on perl monks as well as the Documentation on the CPAN Switch module. If after reading this you feel I missed a post or something, please let me know.
To me, the Switch module seems like overkill for what I want to accomplish. Plus the comment in the module doc itself "There are undoubtedly serious bugs lurking somewhere in code this funky :-)" gives me pause. While I appreciate the candor, it makes me not want to use it for something simple unless there's no other choice. You know "Keep It Simple Stupid!"
Anyhow, after reviewing what I could find, it seemed to me that there must be some way to do it like a jump table.
Now, I know goto is usually shunned by programmers (myself included) but as
distastefull as it can be at times, it seems to be useful in this case. The code below handles known/unknown cases. If the programmer can guarantee only valid cases there's a more simple "Switch" that is commented out in the example.
So, basically what I am asking for is feedback/constructive criticism of the approach shown below.
Being relatively new to perl I am wondering if I am overlooking something important. This seems too simple of an approach to not be mentioned somewhere... UNLESS it's flawed :-)
Note: I just made a few test cases for my own sanity checking, there's nothing special about them.
Thanks for any help/comments.
#!/usr/bin/perl -w use strict; sub HandleSomething { my $option = shift; # SWITCH:{ goto 'CASE_'.$option; # Use if always good cases SWITCH:{$_='CASE_'.$option; eval("goto $_"); $_= 'DEFAULT' if ($@) +; goto $_; CASE_1: print "Case 1\n"; last SWITCH; CASE_4: print "Case 4: "; for (1..4) { print $_; } print "\n"; last SWITCH; CASE_FOUR: print "Case FOUR\n"; last SWITCH; CASE_9: print "Case 9\n"; return "Because I can"; CASE_WHAT: ; CASE_STR: print "Case STRING on $option\n"; last SWITCH; DEFAULT: print qq|Undefined Case "$option"\n|; } } my @testCases = ( 1, 4, 'FOUR', '9','WHAT',"STR", 2, 'nine'); my $more = { tst => 4, tst4 => 'FOUR', tst5 => "Opps" }; print '-' x 50 . "\n"; for (@testCases) { HandleSomething $_; } print '-' x 50 . "\n"; for (sort values %{$more}) { HandleSomething $_; }
In reply to Simple Switch statement by knexus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |