Your skill will accomplishwhat the force of many cannot PerlMonks

### ternary operator

 on Jan 18, 2013 at 06:27 UTC Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

\$a1=2; \$b1=10; (defined(\$a1 > \$b1)) ? (\$int = (\$a1/\$b1)) : (\$int = (\$b1/\$a1)); print \$int;

wats wrong with this code?

Replies are listed 'Best First'.
Re: ternary operator
by tmharish (Friar) on Jan 18, 2013 at 06:55 UTC
```\$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.
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.
Re: ternary operator
by davido (Archbishop) on Jan 18, 2013 at 06:54 UTC

Obviously, it's not using strict. ;)

Dave

Re: ternary operator
by BrowserUk (Pope) on Jan 18, 2013 at 06:44 UTC

Everything!

With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
Re: ternary operator
by AnomalousMonk (Chancellor) on Jan 18, 2013 at 09:39 UTC

Not enough parentheses.

Create A New User
Node Status?
node history
Node Type: perlquestion [id://1013961]
Approved by baxy77bax
help
Chatterbox?
 [jedikaiti]: This is true

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2018-01-18 20:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
How did you see in the new year?

Results (214 votes). Check out past polls.

Notices?