Pathologically Eclectic Rubbish Lister PerlMonks

Re: ternary operator

by tmharish (Friar)
 on Jan 18, 2013 at 06:55 UTC ( #1013967=note: print w/replies, xml ) Need Help??

```\$a1=2; \$b1=10; (\$a1 > \$b1) ? (\$int = (\$a1/\$b1)) : (\$int = (\$b1/\$a1));
+print \$int;
```\$a1=2; \$b1=10; \$int = (\$a1 > \$b1) ? (\$a1/\$b1) : (\$b1/\$a1); print \$int;
What it should really be:
```use strict   ;
use warnings ;

# Use Better Variable Names.
my \$a1 = 2  ;
my \$b1 = 10 ;

my \$int = ( \$a1 > \$b1 ) ? ( \$a1 / \$b1 ) : ( \$b1 / \$a1 ) ;

print \$int;

Reasoning:

defined(\$int = (\$a1/\$b1)) will always evaluate to true regardless of the values of \$a1 and \$b1. If you want to check if both \$a1 and \$b1 are defined you might want to nest it in there like:
```my \$int = ( defined( \$a1 ) and defined( \$b1 ) ) ? ( ( \$a1 > \$b1 ) ? (
+\$a1 / \$b1 ) : ( \$b1 / \$a1 ) ) : die( '\$a1 and \$b1 need to be defined'
+ ) ;
The other thing to note is that the the Ternary Operator, being an Operator, will return something and so you dont need to do the \$int = in both the if and else parts.

Replies are listed 'Best First'.
Re^2: ternary operator
by frozenwithjoy (Priest) on Jan 18, 2013 at 08:55 UTC
Besides checking whether \$a1 and \$b1 are defined, you'd probably also want to verify that the the smaller value is != 0. By now, we are definitely at the point where insisting on using the ternary operator causes needless issues with readability.

Create A New User
Node Status?
node history
Node Type: note [id://1013967]
help
Chatterbox?
 [Discipulus]: good morning monks! town holiday here.. but super busy Discipulus time is not comarable with money.. when you have a roof and something to eat [Corion]: Hi Discipulus! Busy making the town better? ;) [Discipulus]: the house I hope.. now i'm going on the roof putting some protection for the sun. afternoon 150 km for a water polo training (son, obviously..) [Corion]: Discipulus: Ah - lazy roof-sitting ;) [Corion]: (well, after you've put on the sun protection ;) ) [Corion]: But I should be moving into town as well, do some chores and get my hair cut...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2017-06-29 08:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How many monitors do you use while coding?

Results (655 votes). Check out past polls.