[mplspm]: Howto do switch with fall-through

Eric Estabrooks eric at urbanrage.com
Thu Aug 29 19:03:18 CDT 2002


Dan Oelke wrote:

> I have a perl programming question for you....
>
> I want to create a switch type statement with fall-through like C 
> provides.
>
> I have a script where it does a number of things in different "phases" 
> for lack of a better phrase.  What I figured I could do was to pass in 
> the phase I wanted to start in, and the script would pick up at that 
> phase and and proceed through the rest.  Add an extra flag and I could 
> have it do only that phase.
>
> Here is a code snippet illustrating what I want.
> #-----------------------------------------------
> use strict;
>
> my $onlyFlag = 1;
> $_ = $ARGV[0];
>
> SWITCH: {
>   if (/Deliver/) {
>     print "Deliver\n";
>     if($onlyFlag) {last;}
>   }
>   if (/Baseline/) {
>     print "Baseline\n";
>     if ($onlyFlag) {last;}
>   }
>   if (/Rebase/) {
>     print "Rebase\n";
>     if ($onlyFlag) {last;}
>   }
>   if (/Build/) {
>     print "Build\n";
>     if ($onlyFlag) {last;}
>   }
> }
> #-----------------------------------------------
>
> Except that when I execute
>       perl test.pl Baseline
> I see only "Baseline" instead of "Baseline Rebase Build"


Since you have well defined phase names you could do something like this:

my %phase = ('Default',0,'Deliver',1,'Baseline',2,'Rebase',3,'Build',4);
my @funcs = (\&default,\&deliver,\&baseline,\&rebase,\&build);



my $onlyFlag = 0;
$_ = $ARGV[0];

for (my $i = $phase{$_} || $phase{'Default'}; $i < @funcs; $i++) {
        $funcs[$i]();
        last if $onlyFlag || !$i;
}

# subs
sub default {
        print "Default\n";
}
sub deliver {
        print "Deliver\n";
}
sub baseline {
        print "Baseline\n";
}
sub rebase {
        print "Rebase\n";
}
sub build {
        print "Build\n";
}


Eric




--------------------------------------------------
Minneapolis Perl Mongers mailing list

To unsubscribe, send mail to majordomo at pm.org
with "unsubscribe mpls" in the body of the message.



More information about the Mpls-pm mailing list