Search this site:

Ternary operators, conditionals in the middle

Daniel Silverstone asked on our opinions on ternary operators, and as it seems his blog doesn’t like comments (boo!). I just love them. I really like being as concise as possible, without being cryptic - I find it awful to say if (condition) var = val1; else var = val2; Not only it hides the real intention of your statement (you want to assign a value to var, not just to check for a condition), but it is much more error prone (when I typed the line the first time I did an assignment to var and one to val. Daniel says someone suggested the use of functions… Well, yes, sometimes a function would be fine, as in the classical example - I agree that var = max(val1, val2); is better than var = val1 > val2 ? val1 : val2; …But that’s hardly the most common case. Now, I know we Perl guys are seen by the rest of the world as bizarre creatures with the strangest sense of code grokking abilities… But I love how Perl allows us to show where emphasis is in our statements. For example, $result = 0 unless $success; shows the reader the important part in this statement is the assignment (which only happens if $success is true), while $success or $result = 0; is semantically equivalent, but puts the reader’s attention on the fact we are checking for $success, and the assignment happens as a consequence of that. There is more to programming than letting the computer understand your intentions. Although it is often seen as a write-only language by speakers of other tongues, this level of expresiveness helps reading code. A lot. I happen to like Python quite a bit, but this limits it puts on the programmer always put me off while deciding on using it for a new project. BTW, back to ternary operators: It seems not many Perl programmers use them as often as I do, as for Perl6 there will be a language redesign involving operator Huffman-encoding (this means, the shortest and easiest-to-type operators will be the most common ones)… And the current ternary operator ( ? and : ) will be replaced by a more visible, more lengthy ones ( ?? and :: ) :-(