I like this enough that I will be using it for simple case statements.
You can simplify the syntax of it somewhat and make it read almost like the C version by declaring a sub called switch. It's actually more flexible being able to use (some) strings as well as integers.
Updated: Added check for none label characters in the switch expression in view of Courages concerns, allthough in this version, they just caused the default action without the check, the error reporting is handy.
#! perl -slw use strict; sub switch{ die "Bad switch expression at @{[ caller() ]}\n" unless $_[0] =~ /^\w+$/; eval{ goto "case_$_[0]" } or goto default; } for my $expr ( 1 .. 10, 'fred', "1;system('rm -rf /')" ) { switch( $expr ); { case_1: print '1'; last; case_2: print '2'; last; case_3: print '3'; last; case_4: print '4'; last; case_5: ; case_6: print '5 or 6'; last; case_fred: print 'fred'; last; default: print "default"; } } __END__ P:\test>test 1 2 3 4 5 or 6 5 or 6 default default default default fred Bad switch expression at main P:\test\test.pl8 10
Two things to watch for. The semi-colon after the switch(expr); and the need for a semi-colon after a label without a body (as in case_5: ; above).
I'm actually not quite sure why this latter one is required, but it seems to be. Unless someone can tell me where it is written that you can't have two consequetive labels in perl code, I'd consider this a bug?
In reply to Re: Simple Switch statement
by BrowserUk
in thread Simple Switch statement
by knexus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |