📄 ch7.htm
字号:
things.<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Specify a label called </I><TT><I>OUTER_LOOP</I></TT><I>.<BR>Loop from 0 to 10 using </I><TT><I>$index</I></TT><I>as the loop variable.<BR>If </I><TT><I>$index</I></TT><I> isequal to 5, then exit the loop.<BR>Start an inner loop that repeats while </I><TT><I>$index</I></TT><I>is less than 10.<BR>If </I><TT><I>$index</I></TT><I> is4, then exit out of both inner and outer loops.<BR>INCrement </I><TT><I>$index</I></TT><I>.<BR>Print the value of </I><TT><I>$index</I></TT><I>.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>OUTER_LOOP: for ($index = 0; $index < 10; $index++) { if ($index == 5) { last; } while ($index < 10) { if ($index == 4) { last OUTER_LOOP; } print("inner: index = $index\n"); $index++; } print("outer: index = $index\n");}print("index = $index\n");</PRE></BLOCKQUOTE><P>This program displays:<BLOCKQUOTE><PRE>inner: index = 0inner: index = 1inner: index = 2inner: index = 3index = 4</PRE></BLOCKQUOTE><P>The inner <TT>while</TT> loop iNCrements<TT>$index</TT> while it is less than10. However, before it can reach 10 it must pass 4, which triggersthe <TT>if</TT> statement and exitsboth loops. You can tell that the outer loop also was exited becausethe outer print statement is never executed.<H3><A NAME="ExampleTheInextIKeyword">Example: The <I>next</I> Keyword</A></H3><P>The <TT>next</TT> keyword lets youskip the rest of the statement block and start the next iteration.One use of this behavior could be to select specific array elementsfor processing and ignoring the rest. For example:<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Create an array of 10 elements.<BR>Print the array.<BR>Iterate over the array.<BR>Ignore the third and fifth element.<BR>Change the current element to an asterisk.<BR>Print the array to verify that it has been changed.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>@array = (0..9);print("@array\n");for ($index = 0; $index < @array; $index++) { if ($index == 3 || $index == 5) { next; } $array[$index] = "*";}print("@array\n");</PRE></BLOCKQUOTE><P>This program displays:<BLOCKQUOTE><PRE>0 1 2 3 4 5 6 7 8 9* * * 3 * 5 * * * *</PRE></BLOCKQUOTE><P>This example changes every array element, except the third andfifth, to asterisks regardless of their former values. The nextkeyword forces Perl to skip over the assignment statement andgo directly to the iNCrement/decrement expression. You also canuse the next keyword in nested loops.<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Define a label called </I><TT><I>OUTER_LOOP</I></TT><I>.<BR>Start a for loop that iterates from 0 to 3 using </I><TT><I>$row</I></TT><I>as the loop variable.<BR>Start a for loop that iterates from 0 to 3 using </I><TT><I>$col</I></TT><I>as the loop variable.<BR>Display the values of </I><TT><I>$row</I></TT><I>and </I><TT><I>$col</I></TT><I> andmention that the code is inside the inner loop.<BR>If </I><TT><I>$col</I></TT><I> isequal to 1, start the next iteration of loop near the label </I><TT><I>OUTER_LOOP</I></TT><I>.<BR>Display the values of </I><TT><I>$row</I></TT><I>and </I><TT><I>$col</I></TT><I> andmention that the code is inside the outer loop.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>OUTER_LOOP: for ($row = 0; $row < 3; $row++) { for ($col = 0; $col < 3; $col++) { print("inner: $row,$col\n"); if ($col == 1) { next OUTER_LOOP; } } print("outer: $row,$col\n\n"); }</PRE></BLOCKQUOTE><P>This program displays:<BLOCKQUOTE><PRE>inner: 0,0inner: 0,1inner: 1,0inner: 1,1inner: 2,0inner: 2,1</PRE></BLOCKQUOTE><P>You can see that the <TT>next</TT>statement in the inner loop causes Perl to skip the <TT>print</TT>statement in the outer loop whenever <TT>$col</TT>is equal to 1.<H3><A NAME="ExampleTheIredoIKeyword">Example: The <I>redo</I> Keyword</A></H3><P>The <TT>redo</TT> keyword causes Perlto restart the current statement block. Neither the iNCrement/decrementexpression nor the conditional expression is evaluated beforerestarting the block. This keyword is usually used when gettinginput from outside the program, either from the keyboard or froma file. It is essential that the conditions that caused the <TT>redo</TT>statement to execute can be changed so that an endless loop doesnot occur.<P>This example will demonstrate the <TT>redo</TT>keyword with some keyboard input:<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Start a statement block.<BR>Print a prompt asking for a name.<BR>Read a string from the keyboard. Control is returned to the programwhen the user of the program presses the Enter key.<BR>Remove the newline character from the end of the string.<BR>If the string has zero length, it means the user simply pressedthe Enter key without entering a name, so display an error messageand redo the statement block.<BR>Print a thank-you message with the name in uppercase characters.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>print("What is your name? "); $name = <STDIN>; chop($name); if (! length($name)) { print("Msg: Zero length input. Please try again\n"); redo; } print("Thank you, " . uc($name) . "\n");}<BR></PRE></BLOCKQUOTE><p><CENTER><TABLE BORDERCOLOR=#000000 BORDER=1 WIDTH=80%><TR><TD><B>Tip</B></TD></TR><TR><TD><BLOCKQUOTE>It's worth noting that the statement block in this example acts like a single-time loop construct. You can use any of the jump keywords inside the statement block.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>The <TT>redo</TT> statement helpsyou to have more straightforward program flow. Without it, youwould need to use a <TT>do...until</TT>loop. For example:<P><IMG SRC="pseudo.gif" BORDER=1 ALIGN=RIGHT><p><BLOCKQUOTE><I>Start a </I><TT><I>do...until</I></TT><I>statement.<BR>Print a prompt asking for a name.<BR>Read a string from the keyboard. Control is returned to the programwhen the user of the program presses the enter key.<BR>Remove the newline character from the end of the string.<BR>If the string has zero length, it means the user simply pressedthe Enter key without entering a name, so display an error message.<BR>Evaluate the conditional expression. If true, then the user entereda name and the loop can end.<BR>Print a thank you message with the name in uppercase characters.</I></BLOCKQUOTE><BLOCKQUOTE><PRE>do { print("What is your name? "); $name = <STDIN>; chomp($name); if (! length($name)) { print("Msg: Zero length input. Please try again\n"); }} until (length($name));print("Thank you, " . uc($name) . "\n");</PRE></BLOCKQUOTE><P>The <TT>do...until</TT> loop is lessefficient because the length of <TT>$name</TT>needs to be tested twice. Because Perl has so many ways to doany given task, it pays to think about which method is more efficientbefore implementing your ideas.<H3><A NAME="ExampleTheIgotoIKeyword">Example: The <I>goto</I> Keyword</A></H3><P>The <TT>goto</TT> statement lets yourprogram jump directly to any label. However, because Perl alsoprovides the loop statements and other jump keywords, its useis looked down on by most programmers. Using the <TT>goto</TT>in your programs frequently causes your program logic to becomeconvoluted. If you write a program that you feel needs a <TT>goto</TT>in order to run, then use it-but first, try to restructure theprogram to avoid it.<H2><A NAME="Summary"><FONT SIZE=5 COLOR=#FF0000>Summary</FONT></A></H2><P>This chapter was devoted to learning about three types of statements:decision, loop, and jump. Decision statements use the <TT>if</TT>keyword to execute a statement block depending on the evaluationof conditional expressions. Loop statements also execute a statementblock based on a given condition, but they will repeatedly executethe block until the condition is true or while the condition istrue. Jump statements are used to restart statement blocks, skipto the next iteration in a loop, and exit loops prematurely.<P>The <TT>if</TT> statement can be usedwith an <TT>else</TT> clause to chooseone of two statement blocks to execute. Or, you can use the <TT>elsif</TT>clause to choose from among more than two statement blocks.<P>Both the <TT>while </TT>and <TT>until</TT>loop statements have two forms. One form (the <TT>do...</TT>form) executes a statement block and then tests a conditionalexpression, and the other form tests the condition before executingthe statement block.<P>The <TT>for</TT> loops are the mostcomplicated type of loop because they involve three expressionsin addition to a statement block. There is an initialization expression,a conditional expression, and an iNCrement/decrement expression.The initialization expression is evaluated first, then the conditionalexpression. If the conditional expression is false, the statementblock is executed. Next, the iNCrement/decrement expression isevaluated and the loop starts again with the conditional expression.<P><TT>Foreach</TT> loops are used toiterate through an array. Each element in the array is assignedto a local variable as the loop progresses through the array.If you don't specify a local variable, Perl will use the <TT>$</TT>special variable. You need to be careful when changing the valueof the local variable because it uses the call by refereNCe scheme.Therefore, any change to the local variable will be reflectedin the value of the array element outside the <TT>foreach</TT>loop.<P>The <TT>last</TT> keyword is usedto jump out of the current statement block. The <TT>next</TT>keyword is used to skip the rest of the statement block and continueto the next iteration of the loop. The <TT>redo</TT>keyword is used to restart the statement block. And finally, the<TT>goto</TT> keyword should not beused because the other jump keywords are more descriptive. Allof the jump keywords can be used with labels so they can be usedinside nested loops.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#FF0000>Review Questions</FONT></A></H2><P>Answers to Review Questions are in Appendix A.<OL><LI>What are the four loop keywords?<LI>What are the four jump keywords?<LI>Which form of the <TT>until</TT>statement is used when the statement block needs to be executedat least oNCe?<LI>What will be displayed when this program executes?<BR><BR><TT>$firstVar = 5;<BR>{<BR> if ($firstVar > 10) {<BR> last;<BR> }<BR> $firstVar++;<BR> redo;<BR>}<BR>print("$firstVar\n");</TT><LI>What is the default name of the local variable in the <TT>foreach</TT>loop?<LI>How is the <TT>next</TT> keyworddifferent from the <TT>redo</TT> keyword?<LI>Why is the comma operator useful in the initialization expressionof a <TT>for</TT> loop?<LI>What is the <TT>shift()</TT> fuNCtionused for?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#FF0000>Review Exercises</FONT></A></H2><OL><LI>Use the <TT>while</TT> loop ina program to count from 1 to 100 in steps of 5.<LI>Use the <TT>for</TT> loop in aprogram to print each number from 55 to 1.<LI>Use an <TT>until</TT> loop, the<TT>next</TT> statement, and the modulusoperator to loop from 0 to 100 and print out "AAA" everySixteenth iteration.<LI>Use the <TT>foreach</TT> loopto determine the smallest element in an array.<LI>Use a <TT>for</TT> loop to iterateover an array and multiple each element by 3.<LI>Use a <TT>do..until</TT> loopand the <TT>each()</TT> fuNCtion toiterate over an associative array looking for an value equal to"AAA." When the element is found, the loop should beended.</OL><HR><CENTER><P><A HREF="ch6.htm"><IMG SRC="pc.gif" BORDER=0 HEIGHT=88 WIDTH=140></A><A HREF="#CONTENTS"><IMG SRC="cc.gif" BORDER=0 HEIGHT=88 WIDTH=140></A><A HREF="index.htm"><IMG SRC="hb.gif" BORDER=0 HEIGHT=88 WIDTH=140></A><A HREF="ch8.htm"><IMG SRC="nc.gif" BORDER=0 HEIGHT=88 WIDTH=140></A><HR WIDTH="100%"></P></CENTER></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -