📄 appa_05.htm
字号:
<html><head><title>Answers to Chapter 6 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 & 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_04.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_06.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr></table></div><h2 class="sect1">A.5. Answers to Chapter 6 Exercises</h2><ol><li><p>Here's one way to do it:</p><blockquote><pre class="code">print reverse <>;</pre></blockquote><p>Well, that's pretty simple! But it works because<tt class="literal">print</tt> is looking for a list of strings to print,which it gets by calling <tt class="literal">reverse</tt> in a listcontext. And <tt class="literal">reverse</tt> is looking for a list ofstrings to reverse, which it gets by using the diamond operator inlist context. So, the diamond returns a list of all of the lines fromall of the files of the user's choice. That list of lines isjust what <i class="command">cat</i> would print out. Now<tt class="literal">reverse</tt> reverses the list of lines, and<tt class="literal">print</tt> prints them out.</p></li><li><p>Here's one way to do it:</p><blockquote><pre class="code">print "Enter some lines, then press Ctrl-D:\n"; # or Ctrl-Zchomp(my @lines = <STDIN>);print "1234567890" x 7, "12345\n"; # ruler line to column 75foreach (@lines) { printf "%20s\n", $_;}</pre></blockquote><p>Here, we start by reading in and chomping all of the lines of text.Then we print the ruler line. Since that's a debugging aid,we'd generally comment-out that line when the program is done.We could have typed <tt class="literal">"1234567890"</tt> again and again,or even used copy-and-paste to make a ruler line as long as weneeded, but we chose to do it this way because it's kind ofcool.</p><p>Now, the <tt class="literal">foreach</tt> loop iterates over the list oflines, printing each one with the <tt class="literal">%20s</tt> conversion.If you chose to do so, you could have created a format to print thelist all at once, without the loop:</p><blockquote><pre class="code">my $format = "%20s\n" x @lines;printf $format, @lines;</pre></blockquote><p>It's a common mistake to get 19-character columns. That happenswhen you say to yourself,<a href="#FOOTNOTE-385">[385]</a> "Hey, why do we<tt class="literal">chomp</tt> the input if we're only going to addthe newlines back on later?" So you leave out the<tt class="literal">chomp</tt> and use a format of<tt class="literal">"%20s"</tt> (without a newline).<a href="#FOOTNOTE-386">[386]</a> And now,mysteriously, the output is off by one space. So, what went wrong?</p><blockquote class="footnote"> <a name="FOOTNOTE-385" /><p>[385]Or to Larry, if he'sstanding nearby.</p> </blockquote><blockquote class="footnote"> <a name="FOOTNOTE-386" /><p>[386]UnlessLarry told you not to do that.</p> </blockquote><p>The problem happens when Perl tries to count the spaces needed tomake the right number of columns. If the user enters<tt class="userinput"><b>hello</b></tt> and a newline, Perl sees<em class="emphasis">six</em> characters, not five, since newline is acharacter. So it prints fourteen spaces and a six-character string,sure that it gives the twenty characters you asked for in<tt class="literal">"%20s"</tt>. Oops.</p><p>Of course, Perl isn't looking at the contents of the string todetermine the width; it merely checks the raw number of characters. Anewline (or another special character, such as a tab or a nullcharacter) will throw things off.<a href="#FOOTNOTE-387">[387]</a></p><blockquote class="footnote"> <a name="FOOTNOTE-387" /><p>[387]As Larry shouldhave explained to you by now.</p> </blockquote></li><li><p>Here's one way to do it:</p><blockquote><pre class="code">print "What column width would you like? ";chomp(my $width = <STDIN>);print "Enter some lines, then press Ctrl-D:\n"; # or Ctrl-Zchomp(my @lines = <STDIN>);print "1234567890" x (($width+9)/10), "\n"; # ruler line as neededforeach (@lines) { printf "%${width}s\n", $_;}</pre></blockquote><p>This is much like the previous one, but we ask for a column widthfirst. We ask for that first because we can't ask for moreinput <em class="emphasis">after</em> the end-of-file indicator, at leaston some systems. Of course, in the real world, you'll generallyhave a better end-of-input indicator when getting input from theuser, as we'll see in later chapters.</p><p>Another change from the previous exercise's answer is the rulerline. We used some math to cook up a ruler line that's at leastas long as we need, as suggested as an "extra credit"part of the exercise. Proving that our math is correct is anadditional challenge. (Hint: Consider possible widths of<tt class="literal">50</tt> and <tt class="literal">51</tt>, and remember thatthe right side operand to <tt class="literal">x</tt> is truncated, notrounded.)</p><p>To generate the format this time, we used the expression<tt class="literal">"%${width}s\n"</tt>, which interpolates<tt class="literal">$width</tt>. The curly braces are required to"insulate" the name from the following<tt class="literal">s</tt>; without the curly braces, we'd beinterpolating <tt class="literal">$widths</tt>, the wrong variable. If youforgot how to use curly braces to do this, though, you could havewritten an expression like <tt class="literal">'%' . $width . "s\n"</tt> toget the same format string.</p><p>The value of <tt class="literal">$width</tt> brings up another case where<tt class="literal">chomp</tt> is vital. If the width isn'tchomped, the resulting format string would resemble<tt class="literal">"%30\ns\n"</tt>. That's not useful.</p><p>People who have seen <tt class="literal">printf</tt> before may havethought of another solution. Because <tt class="literal">printf</tt>comes to us from C, which doesn't have string interpolation, wecan use the same trick that C programmers use. If an asterisk("<tt class="literal">*</tt>") appears in place of a numericfield width in a conversion, a value from the list of parameters willbe used:</p><blockquote><pre class="code">printf "%*s\n", $width, $_;</pre></blockquote></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_04.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_06.htm"><img alt="Next" border="0" src="../gifs/txtnexta.gif" /></a></td></tr><tr><td align="left" valign="top" width="228">A.4. Answers to Chapter 5 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.6. Answers to Chapter 7 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 © 2002</a> O'Reilly & 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 + -