in reply to if/unless and chaining

Given possible states A,B,C,D and the if-elsif-else structure

if( state equals A) { Take action1 } elsif( state equals B) { Take action2 } else { Take action3 }

any given state will cause exactly 1 action to be taken no matter what the value of state.

However using this

unless( state equals A ) { Take action1 } elsunless( state equals B ) { Take action2 } else { Take action3 }

If the state is C or D, by the logic of the statements, actions 1 and 2 would need to be taken; but as the entire block terminates once one condition succeeds, action2 would only ever be performed if the state was A, which is counter-intuative to say the least. Also, when would the else clause be performed?

Effectively, the structure above is equivalent to

unless( state equals A) { Take action1 } elsif ( state equals A) { Take action2 } else { Take action3 }

which is already legal in Perl, but is actually the same as

unless( state equals A) { Take action1 } else { Take action2 }

As action three will never be taken as every state except A will have caused action 1 and then the contruct terminates.


Nah! You're thinking of Simon Templar, originally played (on UKTV) by Roger Moore and later by Ian Ogilvy

Replies are listed 'Best First'.
Re: Re: if/unless and chaining
by John M. Dlugosz (Monsignor) on Nov 06, 2002 at 03:43 UTC
    unless( state equals A ) { Take action1 } elsunless( state equals B ) { Take action2 } else { Take action3 }
    the middle line is the same as
    elsif (state != B) ...
    I agree, don't do that. But not every chain of if/elses is a simple switch statement. I can be testing a number of variables or aspects of the total state, making successively tighter constraints. Think of an && chain with side-effects on each test.
      I may be wrong about this, but I think that the example above logically doesn't make sense. The second conditional statement, elseunless(state equals B) will only be reached if the first conditional is true, i.e. state equals a. Effectively the second test will never be true, because when the state equals b, action 1 will be taken.