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

📄 ch04_04.htm

📁 编程珍珠,里面很多好用的代码,大家可以参考学习呵呵,
💻 HTM
📖 第 1 页 / 共 2 页
字号:
<html><head><title>Loop Statements (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 &amp; Associates, Inc."><meta name="DC.Source" content="" scheme="ISBN"><meta name="DC.Subject.Keyword" content=""><meta name="DC.Title" content="Loop Statements"><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="ch04_03.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="ch04_01.htm">Chapter 4: Statements and Declarations</a></td><td align="right" valign="top" width="172"><a href="ch04_05.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">4.4. Loop Statements</h2><a name="INDEX-1071"></a><a name="INDEX-1072"></a><p>All loop statements have an optional <em class="replaceable">LABEL</em> in their formal syntax.(You can put a label on any statement, but it has a special meaning toa loop.)  If present, the label consists of an identifier followed by acolon.  It's customary to make the label uppercase to avoid potentialconfusion with reserved words, and so it stands out better.  Andalthough Perl won't get confused if you use a label that already has ameaning like <tt class="literal">if</tt> or <tt class="literal">open</tt>, your readers might.<a name="INDEX-1073"></a></p><h3 class="sect2">4.4.1. while and until Statements</h3><a name="INDEX-1074"></a><a name="INDEX-1075"></a><a name="INDEX-1076"></a><a name="INDEX-1077"></a><p>The <tt class="literal">while</tt> statement repeatedly executes the block as long as <em class="replaceable">EXPR</em>is true.  If the word <tt class="literal">while</tt> is replaced by the word <tt class="literal">until</tt>, thesense of the test is reversed; that is, it executes the block only aslong as <em class="replaceable">EXPR</em> remains false.  The conditional is still tested beforethe first iteration, though.</p><p><a name="INDEX-1078"></a><a name="INDEX-1079"></a><a name="INDEX-1080"></a>The <tt class="literal">while</tt> or <tt class="literal">until</tt> statement can have an optional extra block: the <tt class="literal">continue</tt> block.  This block is executed every timethe block is continued, either by falling off the end of the firstblock or by an explicit <tt class="literal">next</tt> (a loop-control operator that goesto the next iteration).  The <tt class="literal">continue</tt> block is not heavily usedin practice, but it's in here so we can define the <tt class="literal">for</tt> looprigorously in the next section.</p><p>Unlike the <tt class="literal">foreach</tt> loop we'll see in amoment, a <tt class="literal">while</tt> loop never implicitly localizes any variables in itstest condition.  This can have "interesting" consequences when<tt class="literal">while</tt> loops use globals for loop variables.  In particular,see the section <a href="ch02_11.htm#ch02-sect-li">Section 4.11.2, "Line Input (Angle) Operator"</a> in <a href="ch02_01.htm">Chapter 2, "Bits and Pieces"</a> for how implicit assignment to the global <tt class="literal">$_</tt> canoccur in certain <tt class="literal">while</tt> loops, along with an example of how to dealwith the problem by explicitly localizing <tt class="literal">$_</tt>.  For other loopvariables, however, it's best to declare them with <tt class="literal">my</tt>, as inthe next example.</p><p><a name="INDEX-1081"></a>A variable declared in the test condition of a <tt class="literal">while</tt> or <tt class="literal">until</tt>statement is visible only in the block or blocks governed by thattest.  It is not part of the surrounding scope.  For example:<blockquote><pre class="programlisting">while (my $line = &lt;STDIN&gt;) {    $line = lc $line;}continue {    print $line;   # still visible}# $line now out of scope here</pre></blockquote>Here the scope of <tt class="literal">$line</tt> extends from its declaration in the controlexpression throughout the rest of the loop construct, including the<tt class="literal">continue</tt> block, but not beyond.  If you want the scope to extendfurther, declare the variable before the loop.</p><h3 class="sect2">4.4.2. for Loops</h3><a name="INDEX-1082"></a><a name="INDEX-1083"></a><p><a name="INDEX-1084"></a><a name="INDEX-1085"></a><a name="INDEX-1086"></a><a name="INDEX-1087"></a>The three-part <tt class="literal">for</tt> loop has three semicolon-separated expressionswithin its parentheses.  These expressions function respectivelyas the initialization, the condition, and the re-initializationexpressions of the loop.  All three expressions are optional (butnot the semicolons); if omitted, the condition is always true.Thus, the three-part <tt class="literal">for</tt> loop can be defined in terms of thecorresponding <tt class="literal">while</tt> loop.  This:<blockquote><pre class="programlisting">LABEL:  for (my $i = 1; $i &lt;= 10; $i++) {      ...  }</pre></blockquote>is like this:<blockquote><pre class="programlisting">{    my $i = 1;  LABEL:    while ($i &lt;= 10) {        ...    }    continue {        $i++;    }}</pre></blockquote>except that there's not really an outer block.  (We just put one there to showhow the scope of the <tt class="literal">my</tt> is limited.)</p><p><a name="INDEX-1088"></a><a name="INDEX-1089"></a>If you want to iterate through two variables simultaneously, justseparate the parallel expressions with commas:<blockquote><pre class="programlisting">for ($i = 0, $bit = 0; $i &lt; 32; $i++, $bit &lt;&lt;= 1) {    print "Bit $i is set\n" if $mask &amp; $bit;}# the values in $i and $bit persist past the loop</pre></blockquote><a name="INDEX-1090"></a></p><p>Or declare those variables to be visible only inside the <tt class="literal">for</tt> loop:<blockquote><pre class="programlisting">for (my ($i, $bit) = (0, 1); $i &lt; 32; $i++, $bit &lt;&lt;= 1) {    print "Bit $i is set\n" if $mask &amp; $bit;}# loop's versions of $i and $bit now out of scope</pre></blockquote>Besides the normal looping through array indices, <tt class="literal">for</tt> can lenditself to many other interesting applications.  It doesn't evenneed an explicit loop variable.  Here's one example thatavoids the problem you get when you explicitly test for end-of-fileon an interactive file descriptor, causing your program to appearto hang.<blockquote><pre class="programlisting">$on_a_tty = -t STDIN &amp;&amp; -t STDOUT;sub prompt { print "yes? " if $on_a_tty }for ( prompt(); &lt;STDIN&gt;; prompt() ) {    # do something}</pre></blockquote><a name="INDEX-1091"></a><a name="INDEX-1092"></a></p><p>Another traditional application for the three-part <tt class="literal">for</tt> loop resultsfrom the fact that all three expressions are optional, and thedefault condition is true.  If you leave out all three expressions, youhave written an infinite loop:<blockquote><pre class="programlisting">for (;;) {    ...}</pre></blockquote>This is the same as writing:<blockquote><pre class="programlisting">while (1) {    ...}</pre></blockquote><a name="INDEX-1093"></a><a name="INDEX-1094"></a><a name="INDEX-1095"></a><a name="INDEX-1096"></a><a name="INDEX-1097"></a></p><p><a name="INDEX-1098"></a><a name="INDEX-1099"></a>If the notion of infinite loops bothers you, we should point out thatyou can always fall out of the loop at any point with anexplicit loop-control operator such as <tt class="literal">last</tt>.  Of course, ifyou're writing the code to control a cruise missile, you may notactually need an explicit loop exit.  The loop will be terminatedautomatically at the appropriate moment.<a href="#FOOTNOTE-3">[3]</a></p><blockquote class="footnote"><a name="FOOTNOTE-3"></a><p>[3] That is, thefallout from the loop tends to occur automatically.</p></blockquote><h3 class="sect2">4.4.3. foreach Loops</h3><a name="INDEX-1100"></a><a name="INDEX-1101"></a><a name="INDEX-1102"></a><p>The <tt class="literal">foreach</tt> loop iterates over a list of values by setting thecontrol variable (<em class="replaceable">VAR</em>) to each successive element of the list:<blockquote><pre class="programlisting">foreach <em class="replaceable">VAR</em> (<em class="replaceable">LIST</em>) {    ...}</pre></blockquote><a name="INDEX-1103"></a></p><p><a name="INDEX-1104"></a>The <tt class="literal">foreach</tt> keyword is just a synonym for the <tt class="literal">for</tt> keyword, so youcan use <tt class="literal">foreach</tt> and <tt class="literal">for</tt> interchangeably, whichever you think ismore readable in a given situation.  If <em class="replaceable">VAR</em> is omitted, the global<tt class="literal">$_</tt> is used.  (Don't worry--Perl can easily distinguish <tt class="literal">for(@ARGV)</tt> from <tt class="literal">for ($i=0; $i&lt;$#ARGV; $i++)</tt> because the lattercontains semicolons.) Here are some examples:<blockquote><pre class="programlisting">$sum = 0; foreach $value (@array) { $sum += $value }for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') {  # do a countdown    print "$count\n"; sleep(1);}for (reverse 'BOOM', 1 .. 10) {             # same thing    print "$_\n"; sleep(1);}for $field (split /:/, $data) {             # any <em class="replaceable">LIST</em> expression    print "Field contains: `$field'\n";}foreach $key (sort keys %hash) {    print "$key =&gt; $hash{$key}\n";}</pre></blockquote><a name="INDEX-1105"></a></p><p>That last one is the canonical way to print out the values of ahash in sorted order.  See the <tt class="literal">keys</tt> and <tt class="literal">sort</tt> entries in<a href="ch29_01.htm">Chapter 29, "Functions"</a> for more elaborate examples.</p><p>There is no way with <tt class="literal">foreach</tt> to tell where you are in a list.You may compare adjacent elements by remembering the previous onein a variable, but sometimes you just have to break down and writea three-part <tt class="literal">for</tt> loop with subscripts.  That's what the other kindof <tt class="literal">for</tt> loop is there for, after all.</p><p><a name="INDEX-1106"></a>If <em class="replaceable">LIST</em> consists entirely of assignable values (meaning variables,generally, not enumerated constants), you can modify each of thosevariables by modifying <em class="replaceable">VAR</em> inside the loop.  That's because the<tt class="literal">foreach</tt> loop index variable is an implicit alias for each item inthe list that you're looping over.  Not only can you modify a singlearray in place, you can also modify multiple arrays and hashes in asingle list:<blockquote><pre class="programlisting">foreach $pay (@salaries) {               # grant 8% raises    $pay *= 1.08;

⌨️ 快捷键说明

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