develooper Front page | perl.beginners | Postings from February 2002

Re: Does Perl have "Case" Statements?

Thread Previous | Thread Next
From:
sachin balsekar
Date:
February 28, 2002 14:17
Subject:
Re: Does Perl have "Case" Statements?
Message ID:
3C7EAFA4.90909@myiris.com
Hi,

Perl as such doesnt have support case structures....

u cud try using block which is almost similar to case struct..

A BLOCK by itself (labeled or not) is semantically equivalent to a loop 
that executes once. Thus you can use any of the loop control statements 
in it to leave or restart the block. (Note that this is NOT true in 
eval{}, sub{}, or contrary to popular belief do{} blocks, which do NOT 
count as loops.) The continue block is optional.

The BLOCK construct is particularly nice for doing case structures.

    SWITCH: {
	if (/^abc/) { $abc = 1; last SWITCH; }
	if (/^def/) { $def = 1; last SWITCH; }
	if (/^xyz/) { $xyz = 1; last SWITCH; }
	$nothing = 1;
    }  

There is no official switch statement in Perl, because there are already 
several ways to write the equivalent. In addition to the above, you 
could write

    SWITCH: {
	$abc = 1, last SWITCH  if /^abc/;
	$def = 1, last SWITCH  if /^def/;
	$xyz = 1, last SWITCH  if /^xyz/;
	$nothing = 1;
    }  



hope this helps...

regards,
sachin balsekar.

Chris wrote:

> I have been looking in the Learning Perl book, and cannot find it.
>
> I am sure that it is just a terminology thing.
>
> In VB {Yeah the old VB again :P) I could do:
>
> Select Case $Junk
>     Case 1
>        Do Something
>     Case 2
>        Do Something
>     Case 3
>        Do Something
>     Case 4
>        Do Something
> End Select
>
> Does Perl have something similar to where I do not have to have one
> humongous IF statement?
>
> I have a file I have to read in, and there are 2 fields I have to look 
> at.  In those two fields, one is a password, and I have to display
> the decrypted password to the admin.
>
> Reading the file is not hard.
>
> Getting the proper fields is not hard.
>
> But the password is based on something "a little different" so it 
> isn't just
> pass the decrypt to it...  I have the workaround I was given to 
> determine it, but that means that I have to read it and look
> for the matching string.
>
> Thus a Case Statement, IMHO, would be the best possible solution - with
> my current knowledge...
>
> :)
>
> TIA!!
>
> Chris
>
>


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About