in reply to Simple Switch statement
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?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Simple Switch statement
by liz (Monsignor) on Sep 13, 2003 at 07:47 UTC | |
by knexus (Hermit) on Sep 14, 2003 at 15:06 UTC | |
by hnhegde (Novice) on Dec 16, 2014 at 11:25 UTC | |
|
Goto out of Sub - Re: Re: Simple Switch statement
by knexus (Hermit) on Sep 14, 2003 at 14:05 UTC | |
by BrowserUk (Patriarch) on Sep 14, 2003 at 14:47 UTC | |
by knexus (Hermit) on Sep 14, 2003 at 15:21 UTC | |
by liz (Monsignor) on Sep 14, 2003 at 15:28 UTC |