Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Ternary conditional operator
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Perl === A traditional if-else construct in [[Perl]] is written: <syntaxhighlight lang="perl"> if ($a > $b) { $result = $x; } else { $result = $y; } </syntaxhighlight> Rewritten to use the conditional operator: <syntaxhighlight lang="perl"> $result = $a > $b ? $x : $y; </syntaxhighlight> The precedence of the conditional operator in Perl is the same as in C, not as in C++. This is conveniently of higher precedence than a [[comma operator]] but lower than the precedence of most operators used in expressions within the ternary operator, so the use of parentheses is rarely required.<ref name="perl5op">{{cite book|last1=Christiansen|first1=Tom|last2=Wall|first2=Larry|first3=Brian D|last3=Foy|authorlink1=Tom Christiansen|authorlink2=Larry Wall|authorlink3=Brian d foy|title=[[Programming Perl]]|date=February 2012|publisher=[[O'Reilly Media]]|location=Sebastopol, CA|isbn=978-0-596-00492-7 |page=123 |edition=Fourth |ref=Programming_Perl_v4 |chapter=Chapter 2 Unary and Binary Operators: Conditional Operator}}</ref> Its associativity matches that of C and C++, not that of PHP. Unlike C but like C++, Perl allows the use of the conditional expression as an [[Value (computer science)#lrvalue|L-value]];<ref name="perldoc_perlop">{{cite web |title=perlop: Conditional Operator |url=https://perldoc.perl.org/perlop.html#Conditional-Operator|website=Perl Programming Documentation|last=Wall|first=Larry|author-link=Larry Wall|access-date=26 January 2019}}</ref> for example: <syntaxhighlight lang="perl"> $a > $b ? $x : $y = $result; </syntaxhighlight> will assign {{code|$result}} to either {{code|$x}} or {{code|$y}} depending on the logical expression's boolean result. The respective precedence rules and associativities of the operators used guarantee that the version absent any parentheses is equivalent to this explicitly parenthesized version: <syntaxhighlight lang="perl"> (($a > $b) ? $x : $y) = $result; </syntaxhighlight> This is equivalent to the if-else version: <syntaxhighlight lang="perl"> if ($a > $b) { $x = $result; } else { $y = $result; } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)