views:

135

answers:

2

I'm trying to write a condition for a nested if statement, but haven't found a good example of using or in if statements. The following elsif condition fails and allows the code nested beneath it to fire if $status == 6:

if ($dt1 > $dt2 ) {do one thing}
elsif(($status != 3) || ($status != 6)) { do something else}
else {do something completely different}

I'd like to avoid having another elsif for each condition as the code that actually resides here is several lines long.

+8  A: 

Your logic is wrong and your elseif block will always return true. I think you mean to use an AND instead of an OR. Given the following snippet

foreach $status (1 .. 10) {
   if (($status != 3) && ($status != 6)) {
      print "$status => if\n";
   } else {
      print "$status => else\n";
   }
}

This will output

1 => if
2 => if
3 => else
4 => if
5 => if
6 => else
7 => if
8 => if
9 => if
10 => if

If it helps your thinking, a conditional that is !something || !somethingElse can always be rewritten as !(something && somethingElse). If you apply this to your case above you'd say !(3 && 6), and seeing as a number cannot be 3 and 6 at the same time, it's always false

MrWiggles
These transformation rules are called [De Morgan's laws](http://en.wikipedia.org/wiki/De_Morgan's_laws).
daxim
+6  A: 

You said you're asking this because the code is several lines long. Fix that problem. :)

   if( $dt1 > $dt2 )                      { do_this_thing() }
elsif( ($status != 3) || ($status != 6) ) { do_this_other_thing() }
else                                      { do_something_completely_different() }

Now you don't have several lines in the block and everything is next to each other. You have to figure out what those conditions will be because any value is either not 3 or not 6. :)

Perhaps you meant to use and:

   if( $dt1 > $dt2 )                   { do_this_thing() }
elsif( $status != 3 and $status != 6 ) { do_this_other_thing() }
else                                   { do_something_completely_different() }
brian d foy
Certain values created by e.g. `Perl6::Junction` might disagree :-)
rafl
I was thinking about junctions, but I'm guessing that that is not the problem here. :)
brian d foy