📄 ch6.htm
字号:
<HTML><HEAD><TITLE>Chapter 6 -- Statements</TITLE><META></HEAD><BODY TEXT="#000000" BGCOLOR="#FFFFFF" LINK="#0000EE" VLINK="#551A8B" ALINK="#CE2910"><H1><FONT SIZE=6 COLOR=#FF0000>Chapter 6</FONT></H1><H1><FONT SIZE=6 COLOR=#FF0000>Statements</FONT></H1><HR><P><CENTER><B><FONT SIZE=5>CONTENTS</FONT></B></CENTER><UL><LI><A HREF="#UnderstandingExpressions">Understanding Expressions</A><LI><A HREF="#StatementBlocks">Statement Blocks</A><LI><A HREF="#StatementBlocksandLocalVariables">Statement Blocks and Local Variables</A><LI><A HREF="#StatementTypes">Statement Types</A><UL><LI><A HREF="#ExampleUsingtheifModifier">Example: Using the if Modifier</A><LI><A HREF="#ExampleUsingtheunlessModifier">Example: Using the unless Modifier</A><LI><A HREF="#ExampleUsingtheuntilModifier">Example: Using the until Modifier</A><LI><A HREF="#ExampleUsingthewhileModifier">Example: Using the while Modifier</A></UL><LI><A HREF="#Summary">Summary</A><LI><A HREF="#ReviewQuestions">Review Questions</A><LI><A HREF="#ReviewExercises">Review Exercises</A></UL><HR><P>If you look at a Perl program from a very high level, it is madeof statements. <I>Statements</I> are a complete unit of instructionfor the computer to process. The computer executes each statementit sees-in sequeNCe-until a jump or braNCh is processed.<P>Statements can be very simple or very complex. The simplest statementis this<BLOCKQUOTE><PRE>123;</PRE></BLOCKQUOTE><P>which is a numeric literal followed by a semicolon. The semicolonis very important. It tells Perl that the statement is complete.A more complicated statement might be<BLOCKQUOTE><PRE>$bookSize = ($numOfPages >= 1200 ? "Large" : "Normal");</PRE></BLOCKQUOTE><P>which says if the number of pages is 1,200 or greater, then assign<TT>"Large"</TT> to <TT>$bookSize;</TT>otherwise, assign <TT>"Normal"</TT>to <TT>$bookSize</TT>.<P>In Perl, every statement has a value. In the first example, thevalue of the statement is <TT>123</TT>.In the second example, the value of the statement could be either<TT>"Large"</TT> or <TT>"Normal"</TT>depending on the value of <TT>$numOfPages</TT>.The last value that is evaluated becomes the value for the statement.<P>Like human language in which you put statements together fromparts of speech-nouns, verbs, and modifiers-you can also breakdown Perl statements into parts. The parts are the literals, variables,and fuNCtions you have already seen in the earlier chapters ofthis book.<P>Human language phrases-like, "walk the dog"-also havetheir counterparts in computer languages. The computer equivalentis an expression. <I>Expressions</I> are a sequeNCe of literals,variables, and fuNCtions connected by one or more operators thatevaluate to a single value-scalar or array. An expression canbe promoted to a statement by adding a semicolon. This was donefor the first example earlier. Simply adding a semicolon to theliteral made it into a statement that Perl could execute.<P>Expressions may have side effects, also. FuNCtions that are calledcan do things that are not immediately obvious (like setting globalvariables) or the pre- and post-iNCrement operators can be usedto change a variable's value.<P>Let's take a short diversion from our main discussion about statementsand look at expressions in isolation. Then we'll return to statementsto talk about statement blocks and statement modifiers.<H2><A NAME="UnderstandingExpressions"><FONT SIZE=5 COLOR=#FF0000>Understanding Expressions</FONT></A></H2><P>You can break the universe of expressions up into four types:<UL><LI>Simple Expressions<LI>Simple Expressions with Side Effects<LI>Simple Expression with Operators<LI>Complex Expressions</UL><P><I>Simple expressions </I>consist of a single literal or variable.Table 6.1 shows some examples. Not much can be said about theseexpressions because they are so basic. It might be a matter forsome debate whether or not an array or associative array variablecan be considered a simple expression. My vote is yes, they can.The confusion might arise because of the notation used to describean array or associative array. For example, an array can be specifiedas <TT>(12, 13, 14)</TT>. You cansee this specification as three literal values surrounded by parenthesesor one array. I choose to see one array which fits the definitionof a simple expression-a single variable.<BR><P><CENTER><B>Table 6.1 The Simplest Perl Expressions</B></CENTER><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD WIDTH=211><I>Simple Expression</I></TD><TD WIDTH=192><I>Description</I></TD></TR><TR><TD WIDTH=211><TT>123</TT></TD><TD WIDTH=192>Integer literal</TD></TR><TR><TD WIDTH=211><TT>Chocolate is great!</TT></TD><TD WIDTH=192>String literal</TD></TR><TR><TD WIDTH=211><TT>(1, 2, 3)</TT></TD><TD WIDTH=192>Array literal</TD></TR><TR><TD WIDTH=211><TT>$numPages</TT></TD><TD WIDTH=192>Variable</TD></TR></TABLE></CENTER><P><I>Simple expressions with side effects </I>are the next typeof expression we'll examine. A side effect is when a variable'svalue is changed by the expression. Side effects can be causedusing any of the unary operators: <TT>+</TT>,-, <TT>++</TT>, --. These operatorshave the effect of changing the value of a variable just by theevaluation of the expression.No other Perl operators have thiseffect-other than the assignment operators, of course. FuNCtioncalls can also have side effects- especially if local variableswere not used and changes were made to global variables. Table6.2 shows examples of different side effects.<BR><P><CENTER><B>Table 6.2 Perl Expressions with Side Effects</B></CENTER><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD WIDTH=169><I>Simple Expression</I></TD><TD WIDTH=306><I>Description</I></TD></TR><TR><TD WIDTH=169><TT>$numPages++</TT></TD><TD WIDTH=306>INCrements a variable</TD></TR><TR><TD WIDTH=169><TT>++$numPages</TT></TD><TD WIDTH=306>INCrements a variable</TD></TR><TR><TD WIDTH=169><TT>chop</TT>(<TT>$firstVar</TT>)</TD><TD WIDTH=306>Changes the value of <TT>$firstVar</TT>-a global variable</TD></TR><TR><TD WIDTH=169><TT>sub</TT> <TT>firstsub</TT> { <TT>$firstVar</TT> = 10; }</TD><TD WIDTH=306>Also changes <TT>$firstVar</TT></TD></TR></TABLE></CENTER><P><P>Note that when the expressions <TT>$numPages++</TT>and <TT>++$numPages</TT> are evaluated,they have the same side effect even though they evaluate to differentvalues. The first evaluates to <TT>$numPages</TT>,and the second evaluates to <TT>$numPages+ 1</TT>. The side effect is to iNCrement <TT>$numPages</TT>by 1.<P>The <TT>firstsub()</TT> fuNCtion shownin Table 6.2 changes the value of the <TT>$firstVar</TT>variable, which has a global scope. This can also be considereda side effect, especially if <TT>$firstVar</TT>should have been declared as a local variable.<P><I>Simple expressions with operators</I> are expressions thatiNClude one operator and two operands. Any of Perl's binary operatorscan be used in this type of expression. Table 6.3 shows a fewexamples of this type of expression.<BR><P><CENTER><B>Table 6.3 Perl Expressions with Operators</B></CENTER><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD WIDTH=181><I>Simple Expression</I></TD><TD WIDTH=294><I>Description</I></TD></TR><TR><TD WIDTH=181><TT>10 + $firstVar</TT></TD><TD WIDTH=294>Adds ten to <TT>$firstVar</TT></TD></TR><TR><TD WIDTH=181><TT>$firstVar . "AAA"</TT></TD><TD WIDTH=294>CoNCatenates <TT>$firstVar</TT> and <TT>"AAA"</TT></TD></TR><TR><TD WIDTH=181><TT>"ABC" x 5</TT></TD><TD WIDTH=294>Repeats <TT>"ABC"</TT> five times</TD></TR></TABLE></CENTER><P><P>Another way of viewing <TT>10 +</TT><TT>$firstVar</TT> is as <I>simpleexpression plus simple expression</I>. Thus, you can say thata simple expression with an operator is defined as two simpleexpressions connected by an operator. When computer programmersdefine something in terms of itself, we call it <I>recursion</I>.Each time a recursion is done, the expression is broken down intosimpler and simpler pieces until the computer can evaluate thepieces properly.<P>A <I>complex expression</I> can use any number of literals, variables,operators, and fuNCtions in any sequeNCe. Table 6.4 shows somecomplex expressions.<BR><P><CENTER><B>Table 6.4 Complex Perl Expressions</B></CENTER><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><I>Complex Expression</I></TD></TR><TR><TD><BLOCKQUOTE><TT>(10 + 2) + 20 / (5 ** 2)<BR>20 - (($numPages - 1) * 2)<BR>(($numPages++ / numChapters) * (1.5 / log(10)) + 6)</TT></BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>There is an infinite number of expressions you can form with thePerl operator set. You can get extremely complicated in your useof operators and fuNCtions if you are not careful. I prefer tokeep the expressions short, easy to document, and easy to maintain.<BR><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Tip</B></TD></TR><TR><TD><BLOCKQUOTE>Sometimes it is difficult to tell whether you have enough closing parentheses for all of your opening parentheses. Starting at the left, count each open parenthesis, and when you find a closing parenthesis, subtract one from the total. If you reach zero at the end of the expression, the parentheses are balaNCed.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>Now we'll go back to looking at statements.<H2><A NAME="StatementBlocks"><FONT SIZE=5 COLOR=#FF0000>Statement Blocks</FONT></A></H2><P>A <I>statement block </I>is a group of statements surrounded bycurly braces. Perl views a statement block as one statement. Thelast statement executed becomes the value of the statement block.This means that any place you can use a single statement-likethe <TT>map</TT> fuNCtion-you canuse a statement block. You can also create variables that arelocal to a statement block. So, without going to the trouble ofcreating a fuNCtion, you can still isolate one bit of code fromanother.<P>Here is how I frequently use a statement block:<BLOCKQUOTE><PRE>$firstVar = 10;{ $secondVar >>= 2; $secondVar++;}$thirdVar = 20;</PRE></BLOCKQUOTE><P>The statement block serves to emphasize that the inner code isset apart from the rest of the program. In this case, the initializationof <TT>$secondVar</TT> is a bit morecomplex than the other variables. Using a statement block doesnot change the program execution in any way; it simply is a visualdevice to mark sections of code and a way to create local variables.<H2><A NAME="StatementBlocksandLocalVariables"><FONT SIZE=5 COLOR=#FF0000>Statement Blocks and Local Variables</FONT></A></H2><P>Normally, it's a good idea to place all of your variable initializationat the top of a program or fuNCtion. However, if you are maintainingsome existing code, you may want to use a statement block andlocal variables to minimize the impact of your changes on therest of the code-especially if you have just been handed responsibilityfor a program that someone else has written.<P>You can use the <TT>my()</TT> fuNCtionto create variables whose scope is limited to the statement block.This technique is very useful for temporary variables that won'tbe needed elsewhere in your program. For example, you might havea complex statement that you'd like to break into smaller onesso that it's more understandable. Or you might want to insertsome <TT>print</TT> statements tohelp debug a piece of code and need some temporary variables toaccommodate the <TT>print</TT> statement.<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Assign ten to </I><TT><I>$firstVar</I></TT><I>.<BR>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -