in reply to Re^4: Perl can do it, take 1 (sentence generation)
in thread Perl can do it, take 1 (sentence generation)
That's quite clever, but that is what I would classify as a 'trick' on the basis that if else elsif are designed conditional invocation of blocks of code.
The ternary is specifically designed for conditional assignment of values. Not many people baulk at using
. The only problem here is that there are two conditions instead of one, requiring the use of chained ternaries. But then, noone baulks at using nested or chained ifs, and the structure of the code is identical.my $min = ( $x < $min ) ? $x : $min;
And is it really any clearer?
#! perl -slw use strict; for ( 1 .. 3 ) { print do{ if( $_ == 1 ) { 'one' } elsif( $_ == 2 ) { 'two' } else{ 'three' } }; print $_ == 1 ? 'one' : $_ == 2 ? 'two' : 'three'; }
To my eyes, the former is not even slightly clearer than the latter, but then I use this construct freely, when applicable and so I am used to seeing it and it presents me with no problems to read it. Especially if it is formatted well.
Indeed. The only reason why some of Perl's more obscure contructs are eshewed by some, is because they are obscure. It's a self-propogating argument. If more people used them, they would less obscure--more familiar--and the reason for not using them diminishes.
I'd go even further and say that using the appropriate operators for the operation has further benefits:
By this I mean that it forces a separation between different operations in a way that clarifies the code.
Example: Given the code:
my $var; if( <cond1> ) { $var = <somevalue>; } elsif( <cond2> ) { $var = <someothervalue>; } else { $var = <default>; }
A spec change or bug fix results in this modification:
my $var; if( <cond1> ) { $var = <somevalue>; doSomething; } elsif( <cond2> ) { $var = <someothervalue>; doSomethingElse; } else { $var = <default>; }
I would much rather see that coded as:
my $var = <cond1> ? <somevalue> : <cond2> ? <someothervalue> : <default>; doSomething if $var == <somevalue>; doSomethingElse if $var == <someothervalue>;
To me, it much more clearly captures the semantics of the code.
I'm as guilty as the next man, perhaps more so, of scanning a piece of code and seeing what I think it does instead of what it actually does. If code that does conditional assignment to a variable, looks like an assignment to a variable (with conditions)
, That is more likely to register as that than if it looks like a declaration of a variable followed by a set of conditional blocks of code:my $var = ......;
my $var; if( ... ) { $var = ...; } elseif( ... ) { $var = ...; } else { $var = ...; }
Where the primary purpose of the code is lost in it's construction.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: Perl can do it, take 1 (sentence generation)
by fergal (Chaplain) on Jun 21, 2005 at 17:07 UTC | |
by BrowserUk (Patriarch) on Jun 21, 2005 at 17:21 UTC | |
by fergal (Chaplain) on Jun 21, 2005 at 17:59 UTC |