1834080 Members
2405 Online
110063 Solutions
New Discussion

ifelse + perl

 
network_4
Advisor

ifelse + perl

Hi,

I am having a script where too many if else are using can any one advice how to use switch statement.

Script is like this

if (($var1 eq $var2)) && ($op1 < $op2)) {
print "HI";
}
elsif (($var1 < $var2)) && ($op1 > $op2)) {
print "OK";
}
elsif... and so on
3 REPLIES 3
Maxim Yakimenko
Super Advisor

Re: ifelse + perl

google, ask him "perl switch statement"
Ralph Grothe
Honored Contributor

Re: ifelse + perl

There is no real need in Perl for a switch statement, though many people accustomed to it from C etc. seem to miss this.
There are many ways to implement a switch with common Perl idioms.
Please, run "perldoc -q switch"
or see the "Basic BLOCKs and Switch Statements" section of "perldoc perlsyn".
Also may be found here:

http://perldoc.perl.org/perlsyn.html#Basic-BLOCKs-and-Switch-Statements
Madness, thy name is system administration
H.Merijn Brand (procura
Honored Contributor

Re: ifelse + perl

Drat, I'm sure I replied earlier.
perl up to and including 5.8.x does not have a switch statement, even though many people (think they) need it.
There is a switch statement in the upcoming 5.10 release, which also supports smart matching, but as long as that release is not yet available, it won't help you.

On CPAN, there is a Switch module, but I strongly advice NOT using it, as it is based on source filtering, and wil;l defenitely bring more trouble than good in the longer scripts.

You can make a dispatch table if that suits your needs, something like:

my %dt = (
"-1:-1" => sub {
print "var1 < var2 and op1 < op2\n";
},
:
:
"1:0" => sub {
print "var1 > var 2 & op1 = op2\n";
},
"1:1" => sub {
die "var2 > var1 & op2 > op1: should not happen\n";
},
);

$dt{($var1 <=> $var2).":".($op1 <=> $op2)}->();

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn