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

📄 appa_04.htm

📁 by Randal L. Schwartz and Tom Phoenix ISBN 0-596-00132-0 Third Edition, published July 2001. (See
💻 HTM
字号:
<html><head><title>Answers to Chapter 5 Exercises (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="appa_03.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="appa_05.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr></table></div><h2 class="sect1">A.4. Answers to Chapter 5 Exercises</h2><ol><li><p>Here's one way to do it:</p><blockquote><pre class="code">my %last_name = qw{  fred flintstone  barney rubble  wilma flintstone};print "Please enter a first name: ";chomp(my $name = &lt;STDIN&gt;);print "That's $name $last_name{$name}.\n";</pre></blockquote><p>In this one, we used a <tt class="literal">qw//</tt> list (with curlybraces as the delimiter) to initialize the hash. That's finefor this simple data set, and it's easy to maintain becauseeach data item is a simple given name and simple family name, withnothing tricky. But if your data might contain spaces -- forexample, if <tt class="literal">robert</tt> <tt class="literal">de niro</tt> or<tt class="literal">mary kay place</tt> were to visit Bedrock -- thissimple method wouldn't work so well.</p><p>You might have chosen to assign each key/value pair separately,something like this:</p><blockquote><pre class="code">my %last_name;$last_name{"fred"} = "flintstone";$last_name{"barney"} = "rubble";$last_name{"wilma"} = "flintstone";</pre></blockquote><p>Note that (if you chose to declare the hash with<tt class="literal">my</tt>, perhaps because <tt class="literal">use</tt><tt class="literal">strict</tt> was in effect), you must declare the hashbefore assigning any elements. You can't use<tt class="literal">my</tt> on only part of a variable, like this:</p><blockquote><pre class="code">my $last_name{"fred"} = "flintstone";  # Oops!</pre></blockquote><p>The <tt class="literal">my</tt> operator works only with<em class="emphasis">entire</em> variables, never with just one element ofan array or hash. Speaking of lexical variables, you may have noticedthat the lexical variable <tt class="literal">$name</tt> is being declaredinside of the <tt class="literal">chomp</tt> function call; it is fairlycommon to declare each <tt class="literal">my</tt> variable as it isneeded, like this.</p><p>This is another case where <tt class="literal">chomp</tt> is vital. Ifsomeone enters the five-character string <tt class="literal">"fred\n"</tt>and we fail to <tt class="literal">chomp</tt> it, we'll be lookingfor <tt class="literal">"fred\n"</tt> as an element of the hash -- andit's not there. Of course, <tt class="literal">chomp</tt> alonewon't make this bulletproof; if someone enters <tt class="literal">"fred\n"</tt> (with a trailing space), we don't have a way withwhat we've seen so far to tell that they meant<tt class="literal">fred</tt>.</p><p>If you added a check whether the given key <tt class="literal">exists</tt>in the hash, so that you'll give the user an explanatorymessage when they misspell a name, give yourself extra points forthat.</p></li><li><p>Here's one way to do it:</p><blockquote><pre class="code">my(@words, %count, $word);     # (optionally) declare our variableschomp(@words = &lt;STDIN&gt;);foreach $word (@words) {  $count{$word} += 1;          # or $count{$word} = $count{$word} + 1;}foreach $word (keys %count) {  # or sort keys %count  print "$word was seen $count{$word} times.\n";}</pre></blockquote><p>In this one, we declared all of the variables at the top. People whocome to Perl from a background in languages like Pascal (wherevariables are always declared "at the top") may find thatway more familiar than declaring variables as they are needed. Ofcourse, we're declaring these because we're pretendingthat <tt class="literal">use strict</tt> may be in effect; by default, Perlwon't require such declarations.</p><p>Next, we use the line-input operator,<tt class="literal">&lt;STDIN&gt;</tt>, in a list context to read all ofthe input lines into <tt class="literal">@words</tt>, and then we<tt class="literal">chomp</tt> those all at once. So<tt class="literal">@words</tt> is our list of words from the input (if thewords were all on separate lines, as they should have been, ofcourse).</p><p>Now, the first foreach loop goes through all of the words. That loopcontains the most important statement of the entire program, thestatement that says to add one to <tt class="literal">$count{$word}</tt>,and put the result back into <tt class="literal">$count{$word}</tt>.Although you could write it either the short way (with the<tt class="literal">+=</tt> operator) or the long way, the short way isjust a little bit more efficient, since Perl has to look up<tt class="literal">$word</tt> in the hash just once.<a href="#FOOTNOTE-384">[384]</a></p><blockquote class="footnote"> <a name="FOOTNOTE-384" /><p>[384]Also,at least in some versions of Perl, the shorter way will avoid awarning about using an undefined value that may crop up with thelonger one. The warning may also be avoided by using the <tt class="literal">++</tt>operator to increment the variable, although wehaven't shown you that operator yet.</p> </blockquote><p>For each word in the first <tt class="literal">foreach</tt> loop, we addone to <tt class="literal">$count{$word}</tt>. So, if the first word is<tt class="literal">fred</tt>, we add one to<tt class="literal">$count{"fred"}</tt>. Of course, since this is the firsttime we've seen <tt class="literal">$count{"fred"}</tt>, it's<tt class="literal">undef</tt>. But since we're treating it as anumber (with the numeric <tt class="literal">+=</tt> operator, or with<tt class="literal">+</tt>, if you wrote it the long way), Perl converts<tt class="literal">undef</tt> to <tt class="literal">0</tt> for us,automatically. The total is <tt class="literal">1</tt>, which is thenstored back into <tt class="literal">$count{"fred"}</tt>.</p><p>The next time through that <tt class="literal">foreach</tt> loop,let's say the word is <tt class="literal">barney</tt>. So, we add oneto <tt class="literal">$count{"barney"}</tt>, bumping it up from<tt class="literal">undef</tt> to <tt class="literal">1,</tt> as well.</p><p>Now let's say the next word is <tt class="literal">fred</tt> again.When we add one to <tt class="literal">$count{"fred"}</tt>, which isalready <tt class="literal">1</tt>, we get <tt class="literal">2</tt>. This goesback into <tt class="literal">$count{"fred"}</tt>, meaning that we'venow seen <tt class="literal">fred</tt> twice.</p><p>When we finish the first <tt class="literal">foreach</tt> loop, then,we've counted how many times each word has appeared. The hashhas a key for each (unique) word from the input, and thecorresponding value is the number of times that word appeared.</p><p>So now, the second <tt class="literal">foreach</tt> loop goes through thekeys of the hash, which are the unique words from the input. In thisloop, we'll see each <em class="emphasis">different</em> word once.For each one, it says something like "<tt class="literal">fred was seen 3times.</tt>"</p><p>If you want the extra credit on this problem, you could put<tt class="literal">sort</tt> before <tt class="literal">keys</tt> to print outthe keys in order. If there will be more than a dozen items in anoutput list, it's generally a good idea for them to be sorted,so that a human being who is trying to debug the program will fairlyquickly be able to find the item he or she wants.</p></li></ol><hr width="684" align="left" /><div class="navbar"><table width="684" border="0"><tr><td align="left" valign="top" width="228"><a href="appa_03.htm"><img alt="Previous" border="0" src="../gifs/txtpreva.gif" /></a></td><td align="center" valign="top" width="228"><a href="index.htm"><img alt="Home" border="0" src="../gifs/txthome.gif" /></a></td><td align="right" valign="top" width="228"><a href="appa_05.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr><tr><td align="left" valign="top" width="228">A.3. Answers to Chapter 4 Exercises</td><td align="center" valign="top" width="228"><a href="index/index.htm"><img alt="Book Index" border="0" src="../gifs/index.gif" /></a></td><td align="right" valign="top" width="228">A.5. Answers to Chapter 6 Exercises</td></tr></table></div><hr width="684" align="left" /><img alt="Library Navigation Links" border="0" src="../gifs/navbar.gif" usemap="#library-map" /><p><p><font size="-1"><a href="copyrght.htm">Copyright &copy; 2002</a> O'Reilly &amp; Associates. All rights reserved.</font></p><map name="library-map"><area shape="rect" coords="1,0,85,94" href="../index.htm"><area shape="rect" coords="86,1,178,103" href="../lwp/index.htm"><area shape="rect" coords="180,0,265,103" href="../lperl/index.htm"><area shape="rect" coords="267,0,353,105" href="../perlnut/index.htm"><area shape="rect" coords="354,1,446,115" href="../prog/index.htm"><area shape="rect" coords="448,0,526,132" href="../tk/index.htm"><area shape="rect" coords="528,1,615,119" href="../cookbook/index.htm"><area shape="rect" coords="617,0,690,135" href="../pxml/index.htm"></map></body></html>

⌨️ 快捷键说明

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