Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Switch equivalent in Perl

Status
Not open for further replies.

RPrinceton

Programmer
Jan 8, 2003
86
US
Hi,
I like using case structure instead of "If" statements because I think they are much more readable so when I learn any new language I always look to see if the language supports the "Case" construct. In perlsyn(1) I found the following "Case" i.e., "Switch" construct.
SWITCH:
{
$abc = 1, last SWITCH if /^abc/;
$def = 1, last SWITCH if /^def/;
$xyz = 1, last SWITCH if /^xyz/;
$nothing = 1;
}
In psuedo code I want to do the following:
Select Case $DBI::err
Case 0
...call successful
Case 1062
"Duplicate database key"
Case Else
"Any other errors"
End Select

How do I code the Perl equivalent?
Hope this is clear.
Please advise.
Thanks in advance.
Regards,
Randall Princeton
 
There are many ways to emulate switch in perl.

One way is to use a hash to map the functions:

%States = (
'Default' => \%front_page,
'Shirt' => \&shirt,
'Sweater' => \&sweater
) ;

if( $States{ $page } ) {
$States{$page}->();
} else {
no_such_page() ;
}

So %States is your switch criteria and you let perl handle the rest.

 
One primary difference between these two is that the first is procedural in nature and will fully support objects, other libraries etc. The second is based on using perl Label's which is more suited to a single script that is running without libraries, objects etc.

Keep these sorts of things in mind as you pick a strategy.

 
Another thing, when testing hash keys, it's best to use the [tt]exists[/tt] function [tt]if(exists $hash{key})[/tt]. [tt]if($hash{key})[/tt] will actually create the key in the hash to test its value. Since it just created it, it's undef and tests false, but if you ever have to do something like looping over keys, it comes up as a key now.

But if you're using it to detect a runtime mode, it shouldn't be that much of a problem, just a good habit to get into. Use [tt]exists[/tt] when you're testing if it exists.

Also, if you're doing modes like that, look at CGI::Application:
----------------------------------------------------------------------------------
...but I'm just a C man trying to see the light
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top