Think of the c compiler doing something like this:
sub CompileSwitch{
my %hash;
my @commands;
my $command = 0;
my $mydefault;
while (@_) {
my $case = shift;
my $code = shift;
if ($case eq "default") {
$mydefault = $code;
last;
}
$hash{$case} = $command++;
push @commands,$code;
}
return sub{
my $case = shift;
my $i = $hash{$case};
if (defined $i) {
# fall through , a C switch doesn't test following cases it
# just goes to the end or till it hits a break
for (;$i<@commands;$i++) {
# execute code
&{$commands[$i]}
}
}
elsif (defined $mydefault) {
&$mydefault;
}
}
}
my $switch = CompileSwitch(
'a'=>sub { print "a"},
'b'=>sub { print "b"},
'c'=>sub { print "c"; last},
'x'=>sub { print "x"},
'y'=>sub { print "y"},
'z'=>sub { print "z"},
'default'=>sub { print "unknown case"}
);
foreach (qw(a b c d e f x y z)) {
print "testing $_\n";
$switch->($_);
print "\n";
}
__OUTPUT__
testing a
abc
testing b
bc
testing c
c
testing d
unknown case
testing e
unknown case
testing f
unknown case
testing x
xyz
testing y
yz
testing z
z
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|