in reply to Useless unless
because that has serious potential problems. Namely, the conditional expression ($x) could be non-idempotent, or it could be expensive to evaluate. (Note that simply being a scalar variable doesn't avoid this problem: it could be tied.)foo() if $x; bar() unless $x;
The workaround is to use a temporary variable:
but that's getting ugly. You may as well use the standard if/else and avoid a temporary.{ | for my $b ( $x ) | for $x -> my $b my $b = $x; | { | { foo() if $b; | foo() if $b; | foo() if $b; bar() unless $b; | bar() unless $b; | bar() unless $b; } | } | }
As for the suggestion of using the trinary operatory, I would just point out that the intended purpose of the trinary operator is as a selector between two expressions rather than two statements — that is, between data rather than code. Of course you can use it to select between expressions which are there for their side-effects... but using the trinary operator in void context is — or should be, to seasoned Perl programmers — as distasteful as using map in void context: Sure, it works, and has no ill effects, but as a matter of style, it's just bad.
Another approach to 'otherwise' would bebut that has the disadvantage of putting the "false" action right next to the 'if', so that a human might (mistakenly) see "... bar() if $x;" which is completely wrong.foo() else bar() if $x;
Anyway, I really like 'otherwise', though I'm not seriously proposing it as an addition to the language. It's too late for such things. :-)
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Useless unless
by Anonymous Monk on Aug 09, 2005 at 09:06 UTC | |
|
Re^2: Useless unless
by Anonymous Monk on Aug 09, 2005 at 09:17 UTC |