Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: ternary conditional help (style)

by tye (Sage)
on Nov 28, 2016 at 21:57 UTC ( #1176745=note: print w/replies, xml ) Need Help??


in reply to ternary conditional help

Certain purveyors of half truths have led me to believe that the "? :" syntax and the "if then else" syntax spring from the same goodly source.

Equivalent uses of them likely produce identical opnodes for Perl to execute. But "if" is meant for use on statements (or blocks of statements). "? :" is meant for use on expressions. The precedence table (for Perl and C and many other similar languages) treat assignment as more like a statement, not just an expression. So, to include an assignment inside of an expression, you usually need to enclose that assignment inside parens.

This can be a good reason to adopt a style that avoids using "? :" to pick between different assignments. On the flip side, I have had people argue that code like:

if( condition() ) { $a = one(); } else { $a = two(); }

is better written, style-wise, like:

$a = condition() ? one() : two();

Which I can agree with in some cases more than others.

- tye        

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1176745]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2022-05-28 21:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (101 votes). Check out past polls.

    Notices?