📄 ch03_16.htm
字号:
<html><head><title>Conditional Operator (Programming Perl)</title><!-- STYLESHEET --><link rel="stylesheet" type="text/css" href="../style/style1.css"><!-- METADATA --><!--Dublin Core Metadata--><meta name="DC.Creator" content=""><meta name="DC.Date" content=""><meta name="DC.Format" content="text/xml" scheme="MIME"><meta name="DC.Generator" content="XSLT stylesheet, xt by James Clark"><meta name="DC.Identifier" content=""><meta name="DC.Language" content="en-US"><meta name="DC.Publisher" content="O'Reilly & Associates, Inc."><meta name="DC.Source" content="" scheme="ISBN"><meta name="DC.Subject.Keyword" content=""><meta name="DC.Title" content="Conditional Operator"><meta name="DC.Type" content="Text.Monograph"></head><body><!-- START OF BODY --><!-- TOP BANNER --><img src="gifs/smbanner.gif" usemap="#banner-map" border="0" alt="Book Home"><map name="banner-map"><AREA SHAPE="RECT" COORDS="0,0,466,71" HREF="index.htm" ALT="Programming Perl"><AREA SHAPE="RECT" COORDS="467,0,514,18" HREF="jobjects/fsearch.htm" ALT="Search this book"></map><!-- TOP NAV BAR --><div class="navbar"><table width="515" border="0"><tr><td align="left" valign="top" width="172"><a href="ch03_15.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="ch03_01.htm">Chapter 3: Unary and Binary Operators</a></td><td align="right" valign="top" width="172"><a href="ch03_17.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr></table></div><hr width="515" align="left"><!-- SECTION BODY --><h2 class="sect1">3.16. Conditional Operator</h2><p><a name="INDEX-982"></a><a name="INDEX-983"></a><a name="INDEX-984"></a>As in C, <tt class="literal">?:</tt> is the onlytrinary operator. It's often called the conditional operator becauseit works much like an if-then-else, except that, since it's anexpression and not a statement, it can be safely embedded within otherexpressions and functions calls. As a trinary operator, its two partsseparate three expressions:<blockquote><pre class="programlisting"><em class="replaceable">COND</em> ? <em class="replaceable">THEN</em> : <em class="replaceable">ELSE</em></pre></blockquote>If the condition <em class="replaceable">COND</em> is true, only the<em class="replaceable">THEN</em> expression is evaluated, and the valueof that expression becomes the value of the entire expression.Otherwise, only the <em class="replaceable">ELSE</em> expression isevaluated, and its value becomes the value of the entire expression.</p><p><a name="INDEX-985"></a><a name="INDEX-986"></a>Scalar or list context propagates downward into the second or thirdargument, whichever is selected. (The first argument is always in scalarcontext, since it's a conditional.)<blockquote><pre class="programlisting">$a = $ok ? $b : $c; # get a scalar@a = $ok ? @b : @c; # get an array$a = $ok ? @b : @c; # get a count of an array's elements</pre></blockquote><a name="INDEX-987"></a><a name="INDEX-988"></a><a name="INDEX-989"></a>You'll often see the conditional operator embedded in lists of valuesto format with <tt class="literal">printf</tt>, since nobody wants toreplicate the whole statement just to switch between two relatedvalues.<blockquote><pre class="programlisting">printf "I have %d camel%s.\n", $n, $n == 1 ? "" : "s";</pre></blockquote>Conveniently, the precedence of <tt class="literal">?:</tt> is higher than acomma but lower than most operators you'd use inside (such as<tt class="literal">==</tt> in this example), so you don't usually have toparenthesize anything. But you can add parentheses for clarity if youlike. For conditional operators nested within the<em class="replaceable">THEN</em> parts of other conditional operators,we suggest that you put in line breaks and indent as if they wereordinary <tt class="literal">if</tt> statements:<blockquote><pre class="programlisting">$leapyear = $year % 4 == 0 ? $year % 100 == 0 ? $year % 400 == 0 ? 1 : 0 : 1 : 0;</pre></blockquote>For conditionals nested within the <em class="replaceable">ELSE</em>parts of earlier conditionals, you can do a similar thing:<blockquote><pre class="programlisting">$leapyear = $year % 4 ? 0 : $year % 100 ? 1 : $year % 400 ? 0 : 1;</pre></blockquote>but it's usually better to line up all the <em class="replaceable">COND</em> and<em class="replaceable">THEN</em> parts vertically:<blockquote><pre class="programlisting">$leapyear = $year % 4 ? 0 : $year % 100 ? 1 : $year % 400 ? 0 : 1;</pre></blockquote>Lining up the question marks and colons can make sense of even fairlycluttered structures:<blockquote><pre class="programlisting">printf "Yes, I like my %s book!\n", $i18n eq "french" ? "chameau" : $i18n eq "german" ? "Kamel" : $i18n eq "japanese" ? "\x{99F1}\x{99DD}" : "camel"</pre></blockquote><a name="INDEX-990"></a>You can assign to the conditional operator<a href="#FOOTNOTE-5">[5]</a> if both the second and thirdarguments are legal lvalues (meaning that you can assign to them),and both are scalars or both are lists (otherwise, Perl won't knowwhich context to supply to the right side of the assignment):<blockquote><pre class="programlisting">($a_or_b ? $a : $b) = $c; # sets either $a or $b to have the value of $c</pre></blockquote>Bear in mind that the conditional operator binds more tightly than thevarious assignment operators. Usually this is what you want (see the<tt class="literal">$leapyear</tt> assignments above, for example), but you can'thave it the other way without using parentheses. Using embeddedassignments without parentheses will get you into trouble, and youmight not get a parse error because the conditional operator can beparsed as an lvalue. For example, you might write this:<blockquote><pre class="programlisting">$a % 2 ? $a += 10 : $a += 2 # WRONG</pre></blockquote>But that would be parsed like this:<blockquote><pre class="programlisting">(($a % 2) ? ($a += 10) : $a) += 2</pre></blockquote></p><blockquote class="footnote"><a name="FOOTNOTE-5"></a><p>[5] This is notnecessarily guaranteed to contribute to the readability of yourprogram. But it can be used to create some cool entries in anObfuscated Perl contest.</p></blockquote><!-- BOTTOM NAV BAR --><hr width="515" align="left"><div class="navbar"><table width="515" border="0"><tr><td align="left" valign="top" width="172"><a href="ch03_15.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="index.htm"><img src="../gifs/txthome.gif" alt="Home" border="0"></a></td><td align="right" valign="top" width="172"><a href="ch03_17.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr><tr><td align="left" valign="top" width="172">3.15. Range Operator</td><td align="center" valign="top" width="171"><a href="index/index.htm"><img src="../gifs/index.gif" alt="Book Index" border="0"></a></td><td align="right" valign="top" width="172">3.17. Assignment Operators</td></tr></table></div><hr width="515" align="left"><!-- LIBRARY NAV BAR --><img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p><font size="-1"><a href="copyrght.htm">Copyright © 2001</a> O'Reilly & Associates. All rights reserved.</font></p><map name="library-map"> <area shape="rect" coords="2,-1,79,99" href="../index.htm"><area shape="rect" coords="84,1,157,108" href="../perlnut/index.htm"><area shape="rect" coords="162,2,248,125" href="../prog/index.htm"><area shape="rect" coords="253,2,326,130" href="../advprog/index.htm"><area shape="rect" coords="332,1,407,112" href="../cookbook/index.htm"><area shape="rect" coords="414,2,523,103" href="../sysadmin/index.htm"></map><!-- END OF BODY --></body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -