⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch10_09.htm

📁 by Randal L. Schwartz and Tom Phoenix ISBN 0-596-00132-0 Third Edition, published July 2001. (See
💻 HTM
📖 第 1 页 / 共 2 页
字号:
<html><head><title>Logical Operators (Learning Perl, 3rd Edition)</title><link rel="stylesheet" type="text/css" href="../style/style1.css" /><meta name="DC.Creator" content="Randal L. Schwartz and Tom Phoenix" /><meta name="DC.Format" content="text/xml" scheme="MIME" /><meta name="DC.Language" content="en-US" /><meta name="DC.Publisher" content="O'Reilly &amp; Associates, Inc." /><meta name="DC.Source" scheme="ISBN" content="0596001320L" /><meta name="DC.Subject.Keyword" content="stuff" /><meta name="DC.Title" content="Learning Perl, 3rd Edition" /><meta name="DC.Type" content="Text.Monograph" /></head><body bgcolor="#ffffff"><img alt="Book Home" border="0" src="gifs/smbanner.gif" usemap="#banner-map" /><map name="banner-map"><area shape="rect" coords="1,-2,616,66" href="index.htm" alt="Learning Perl, 3rd Edition" /><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="ch10_08.htm"><img alt="Previous" border="0" src="../gifs/txtpreva.gif" /></a></td><td align="center" valign="top" width="228"><a href="index.htm"></a></td><td align="right" valign="top" width="228"><a href="ch10_10.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr></table></div><h2 class="sect1">10.9. Logical Operators</h2><p><a name="INDEX-706" /> <a name="INDEX-707" />As you might expect, Perl has all of thenecessary logical operators needed to work with Boolean (true/false)values. For example, it's often useful to combine logical testsby using the logical <a name="INDEX-708" /> <a name="INDEX-709" />AND operator(<tt class="literal">&amp;&amp;</tt>) and the logical<a name="INDEX-710" /><a name="INDEX-711" />OR operator (<tt class="literal">||</tt>):</p><blockquote><pre class="code">if ($dessert{'cake'} &amp;&amp; $dessert{'ice cream'}) {  # Both are true  print "Hooray! Cake and ice cream!\n";} elsif ($dessert{'cake'} || $dessert{'ice cream'}) {  # At least one is true  print "That's still good...\n";} else {  # Neither is true - do nothing (we're sad)}</pre></blockquote><p>There may be a shortcut. If the left side of a logical AND operationis false, the whole thing is false, since logical AND needs bothsides to be true in order to return true. In that case, there'sno reason to check the right side, so it will not even be evaluated.Consider what happens in this example if <tt class="literal">$hour</tt> is<tt class="literal">3</tt>:</p><blockquote><pre class="code">if ( (9 &lt;= $hour) &amp;&amp; ($hour &lt; 17) ) {  print "Aren't you supposed to be at work...?\n";}</pre></blockquote><p>Similarly, if the left side of a logical OR operation is<em class="emphasis">true</em>, the right side will not be evaluated.Consider what happens here if <tt class="literal">$name</tt> is<tt class="literal">fred</tt>:</p><blockquote><pre class="code">if ( ($name eq 'fred') || ($name eq 'barney') ) {  print "You're my kind of guy!\n";}</pre></blockquote><p>Because of this behavior, these operators are called<a name="INDEX-712" />"short-circuit" logicaloperators. They take a short circuit to the result whenever they can.In fact, it's fairly common to rely upon this short-circuitbehavior. Suppose you need to calculate an average:</p><blockquote><pre class="code">if ( ($n != 0) &amp;&amp; ($total/$n &lt; 5) ) {  print "The average is below five.\n";}</pre></blockquote><p>In that example, the right side will be evaluated only if the leftside is true, so we can't accidentally divide by zero and crashthe program.</p><a name="lperl3-CHP-10-SECT-9.1" /><div class="sect2"><h3 class="sect2">10.9.1. The Value of a Short-Circuit Operator</h3><p>Unlike what happens in C (and similar languages), the<a name="INDEX-713" />value of a short-circuitlogical operator is the last part evaluated, not just a Booleanvalue. This provides the same result, in that the last part evaluatedis always true when the whole thing should be true, and it'salways false when the whole thing should be false.</p><p>But it's a much more useful return value. Among other things,the logical OR operator is quite handy for selecting a default value:</p><blockquote><pre class="code">my $last_name = $last_name{$someone} || '(No last name)';</pre></blockquote><p>If <tt class="literal">$someone</tt> is not listed in the hash, the leftside will be <tt class="literal">undef</tt>, which is false. So, thelogical OR will have to look to the right side for the value, makingthe right side the default.<a href="#FOOTNOTE-236">[236]</a> We'll see other uses for thisbehavior later.</p><blockquote class="footnote"> <a name="FOOTNOTE-236" /><p>[236]But do note that in thisidiom the default value won't merely replace<tt class="literal">undef</tt>; it would replace any false value equallywell. That's fine for most names, but don't forget thatzero and the empty string are useful values that are neverthelessfalse. This idiom should be used only when you're willing toreplace <em class="emphasis">any</em> false value with the expression onthe right.</p> </blockquote></div><a name="lperl3-CHP-10-SECT-9.2" /><div class="sect2"><h3 class="sect2">10.9.2. The Ternary Operator, ?:</h3><p>When Larry was deciding which operators to make available in Perl, hedidn't want former <a name="INDEX-714" /><a name="INDEX-715" />C programmers to be left wishingfor something that C had and Perl didn't, so he brought overall of C's operators to Perl.<a href="#FOOTNOTE-237">[237]</a>That meant bringing over C's most confusing operator: the<a name="INDEX-716" /><a name="INDEX-717" />ternary <tt class="literal">?:</tt> operator.While it may be confusing, it can also be quite useful.</p><blockquote class="footnote"> <a name="FOOTNOTE-237" /><p>[237]Well, to be sure,he did leave out the ones that have no use in Perl, such as theoperator that turns a number into the memory address of a variable.And he added several operators (like the string concatenationoperator), which make C folks jealous of Perl.</p> </blockquote><p>The ternary operator is like an <a name="INDEX-718" />if-then-else test,all rolled into an expression. It is called a "ternary"operator because it takes three operands. It looks like this:</p><blockquote><pre class="code">expression ? if_true_expr : if_false_expr</pre></blockquote><p>First, the expression is evaluated to see whether it's true orfalse. If it's true, the second expression is used; otherwise,the third expression is used. Every time, one of the two expressionson the right is evaluated, and one is ignored. That is, if the firstexpression is true, then the second expression is evaluated, and thethird is ignored. If the first expression is false, then the secondis ignored, and the third is evaluated as the value of the wholething.</p><p>In this example, the result of the subroutine<tt class="literal">&amp;is_weekend</tt> determines which string expressionwill be assigned to the variable:</p><blockquote><pre class="code">my $location = &amp;is_weekend($day) ? "home" : "work";</pre></blockquote><p>And here, we calculate and print out an average -- or just aplaceholder line of hyphens, if there's no average available:</p><blockquote><pre class="code">my $average = $n ? ($total/$n) : "-----";print "Average: $average\n";</pre></blockquote><p>You could always rewrite any use of the <tt class="literal">?:</tt>operator as an <tt class="literal">if</tt> structure, often much lessconveniently and less concisely:</p><blockquote><pre class="code">my $average;if ($n) {  $average = $total / $n;} else {  $average = "-----";}print "Average: $average\n";</pre></blockquote>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -