Syntactic Confectionery Delight PerlMonks

### Comment on

 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.

In reply to Re: ternary operator by tmharish
in thread ternary operator by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

• Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
• Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
• Read Where should I post X? if you're not absolutely sure you're posting in the right place.
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
• You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
 For: Use: & & < < > > [ [ ] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?

Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (8)
As of 2017-12-18 17:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
What programming language do you hate the most?

Results (494 votes). Check out past polls.

Notices?