Link to home
Start Free TrialLog in
Avatar of Kobe_Lenjou
Kobe_LenjouFlag for Belgium

asked on

Is there a equiv. for SELECT CASE or SWITCH

I'm searching for the perl equivalent of the VB command SELECT CASE or the identical SWITCH command in C.
Avatar of haystor
haystor

There is no direct equivalent, but something close can be constructed using if-elsif-else...
for instance:

if ($a eq "a") {
   print "a\n";
} elsif ($b eq "b") {
   print "b\n";
} else {
   print "it was neither a nor b\n";
}

The equivalent of fall throughs are best constructed using multiple if's altough the conditionals can become complicated.
I prefer:

SWITCH: {
    $_=$a;
    /^a$/ && do { ..; last SWITCH; };
    /^b$/ && do { ..; last SWITCH; };
    # default follows here
}
Avatar of ozo
or:

for( $a ){
  /^a$/ && do { ..; last }
  /^b$/ && do { ..; last }
  # default follows here
}

or even:

%switch=(
'a'=>sub{print "a\n"},
'b'=>sub{print "b\n"},
);
&{$switch{$a}||sub{print "it was neither a nor b\n"}}

BTW, Kobe_Lenjou, got a server error on your question qid=8630031117,
and couldn't read the last comment you added there.
to find more possibilities to do the same thing, simply read the perlsyn documentation that comes with perl.

perldoc perlsyn

Avatar of Kobe_Lenjou

ASKER

I like the answer of ozo and I want to give you the credit for this one.

Note to ozo,i get the server erorr myself :(
Which answer?  As mgjv says, most of these suggestions, and several more, are given in perlsyn.
(The &{$switch} method is not given in perlsyn, but it can be inferred from perlref.)

If qid=8630031117 has gotten lost, you may want to email linda@experts-exchange.com
or post a question to the customer service area to recover your points
so you can post that question again.
<<__comments__;

Here's a switchy thing I use.  By-the-way I understand switch
is on its way.

__comments__


$switchee = 'b';
SWITCH: {
  if($switchee eq 'a'){
    print "Is a.\n";
    last SWITCH;
  }
  if($switchee eq 'b'){
    print "Is b.\n";
    last SWITCH;
  }
  if($switchee eq 'c'){
    print "Is c.\n";
    last SWITCH;
  }
  if($switchee eq 'd'){
    print "Is d.\n";
    last SWITCH;
  }
  print "Is not a, b, c or d.\n";
  last SWITCH;
}



ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial