📄 ch01_06.htm
字号:
<html><head><title>Control Structures (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="Control Structures"><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="ch01_05.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="ch01_01.htm">Chapter 1: An Overview of Perl</a></td><td align="right" valign="top" width="172"><a href="ch01_07.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">1.6. Control Structures</h2><p><a name="INDEX-285"></a>So far, except for our one large example, all of our examples have beencompletely linear; we executed each command in order. We've seen a fewexamples of using the short-circuit operators to cause a single commandto be (or not to be) executed. While you can write some very usefullinear programs (a lot of CGI scripts fall into this category), you canwrite much more powerful programs if you have conditional expressionsand looping mechanisms. Collectively, these are known as controlstructures. So you can also think of Perl as a control language.</p><p>But to have control, you have to be able to decide things, and to decidethings, you have to know the difference between what's true and what'sfalse.</p><h3 class="sect2">1.6.1. What Is Truth?</h3><p><a name="INDEX-286"></a><a name="INDEX-287"></a><a name="INDEX-288"></a><a name="INDEX-289"></a>We've bandied about the term truth,<a href="#FOOTNOTE-20">[20]</a> and we've mentioned that certain operators return atrue or a false value. Before we go any further, we really ought toexplain exactly what we mean by that. Perl treats truth a littledifferently than most computer languages, but after you've worked withit a while, it will make a lot of sense. (Actually, we hope it'llmake a lot of sense after you've read the following.)</p><blockquote class="footnote"><a name="FOOTNOTE-20"></a><p>[20] Strictly speaking, this isnot true.</p></blockquote><p>Basically, Perl holds truths to be self-evident. That's a glib way ofsaying that you can evaluate almost anything for its truth value. Perluses practical definitions of truth that depend on the type of thingyou're evaluating. As it happens, there are many more kinds of truththan there are of nontruth.</p><p><a name="INDEX-290"></a>Truth in Perl is always evaluated in a scalar context. Other thanthat, no type coercion is done. So here are the rules for the variouskinds of values a scalar can hold:</p><ol><li><p>Any string is true except for <tt class="literal">""</tt> and <tt class="literal">"0"</tt>.<a name="INDEX-291"></a></p></li><li><p>Any number is true except for 0.<a name="INDEX-292"></a></p></li><li><p>Any reference is true.<a name="INDEX-293"></a></p></li><li><p>Any undefined value is false.<a name="INDEX-294"></a></p></li></ol><p>Actually, the last two rules can be derived from the first two. Anyreference (rule 3) would point to something with an address and wouldevaluate to a number or string containing that address, which is never0 because it's always defined. And any undefined value (rule 4) wouldalways evaluate to 0 or the null string.</p><p>And in a way, you can derive rule 2 from rule 1 if you pretend thateverything is a string. Again, no string coercion is actually done to evaluatetruth, but if the string coercion <em class="emphasis">were</em> done, then any numeric valueof 0 would simply turn into the string <tt class="literal">"0"</tt> and be false. Any othernumber would not turn into the string <tt class="literal">"0"</tt>, and so would be true.Let's look at some examples so we can understand this better:<blockquote><pre class="programlisting">0 # would become the string "0", so false.1 # would become the string "1", so true.10 - 10 # 10 minus 10 is 0, would convert to string "0", so false.0.00 # equals 0, would convert to string "0", so false."0" # is the string "0", so false."" # is a null string, so false."0.00" # is the string "0.00", neither "" nor "0", so true!"0.00" + 0 # would become the number 0 (coerced by the +), so false.\$a # is a reference to $a, so true, even if $a is false.undef() # is a function returning the undefined value, so false.</pre></blockquote>Since we mumbled something earlier about truth being evaluated in ascalar context, you might be wondering what the truth value of a listis. Well, the simple fact is, none of the operations in Perl willreturn a list in a scalar context. They'll all notice they're in ascalar context and return a scalar value instead, and then you applythe rules of truth to that scalar. So there's no problem, as long asyou can figure out what any given operator will return in a scalarcontext. As it happens, both arrays and hashes return scalar valuesthat conveniently happen to be true if the array or hash contains anyelements. More on that later.</p><h3 class="sect3">1.6.1.1. The if and unless statements</h3><p><a name="INDEX-295"></a><a name="INDEX-296"></a><a name="INDEX-297"></a><a name="INDEX-298"></a>We saw earlier how a logical operator could function as a conditional. Aslightly more complex form of the logical operators is the <tt class="literal">if</tt>statement. The <tt class="literal">if</tt> statement evaluates a truth condition (that is,a Boolean expression) and executes a block if the condition is true:<blockquote><pre class="programlisting">if ($debug_level > 0) { # Something has gone wrong. Tell the user. print "Debug: Danger, Will Robinson, danger!\n"; print "Debug: Answer was '54', expected '42'.\n";}</pre></blockquote>A block is one or more statements grouped together by a set of braces.Since the <tt class="literal">if</tt> statement executes a block, the braces are required bydefinition. If you know a language like C, you'll notice that this isdifferent. Braces are optional in C if you have a single statement,but the braces are not optional in Perl.<a name="INDEX-299"></a></p><p><a name="INDEX-300"></a>Sometimes, just executing a block when a condition is met isn't enough.You may also want to execute a different block if that condition<em class="emphasis">isn't</em> met. While you could certainly use two <tt class="literal">if</tt> statements, onethe negation of the other, Perl provides a more elegant solution. Afterthe block, <tt class="literal">if</tt> can take an optional second condition, called <tt class="literal">else</tt>,to be executed only if the truth condition is false. (Veteran computerprogrammers will not be surprised at this point.)</p><p><a name="INDEX-301"></a>At times you may even have more than two possible choices. In thiscase, you'll want to add an <tt class="literal">elsif</tt> truth conditionfor the other possible choices. (Veteran computer programmers maywell be surprised by the spelling of"<tt class="literal">elsif</tt>", for which nobody here is going toapologize. Sorry.)<blockquote><pre class="programlisting">if ($city eq "New York") { print "New York is northeast of Washington, D.C.\n";}elsif ($city eq "Chicago") { print "Chicago is northwest of Washington, D.C.\n";}elsif ($city eq "Miami") { print "Miami is south of Washington, D.C. And much warmer!\n";}else { print "I don't know where $city is, sorry.\n";}</pre></blockquote></p><p><a name="INDEX-302"></a>The <tt class="literal">if</tt> and <tt class="literal">elsif</tt> clauses areeach computed in turn, until one is found to be true or the<tt class="literal">else</tt> condition is reached. When one of theconditions is found to be true, its block is executed and allremaining branches are skipped. Sometimes, you don't want to doanything if the condition is true, only if it is false. Using anempty <tt class="literal">if</tt> with an <tt class="literal">else</tt> may bemessy, and a negated <tt class="literal">if</tt> may be illegible; it soundsweird in English to say "if not this is true, do something". In thesesituations, you would use the <tt class="literal">unless</tt> statement:<blockquote><pre class="programlisting">unless ($destination eq $home) { print "I'm not going home.\n";}</pre></blockquote>There is no <tt class="literal">elsunless</tt> though. This is generally construed as afeature.</p><h3 class="sect2">1.6.2. Iterative (Looping) Constructs</h3><p><a name="INDEX-303"></a><a name="INDEX-304"></a> Perl has four mainiterative statement types: <tt class="literal">while</tt>,
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -