📄 ch01_03.htm
字号:
<html><head><title>An Average Example (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 & Associates, Inc."><meta name="DC.Source" content="" scheme="ISBN"><meta name="DC.Subject.Keyword" content=""><meta name="DC.Title" content="An Average Example"><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="ch01_02.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="ch01_01.htm">Chapter 1: An Overview of Perl</a></td><td align="right" valign="top" width="172"><a href="ch01_04.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">1.3. An Average Example</h2><p>Suppose you've been teaching a Perl class, and you're trying to figureout how to grade your students. You have a set of exam scores for eachmember of a class, in random order. You'd like a combined list of allthe grades for each student, plus their average score. You have a textfile (imaginatively named <em class="emphasis">grades</em>) that looks like this:<blockquote><pre class="programlisting">No&#235;l 25Ben 76Clementine 49Norm 66Chris 92Doug 42Carol 25Ben 12Clementine 0Norm 66...</pre></blockquote><a name="INDEX-149"></a>You can use the following script to gather all their scores together,determine each student's average, and print them all out in alphabeticalorder. This program assumes rather naively that you don't have twoCarols in your class. That is, if there is a second entry for Carol,the program will assume it's just another score for the first Carol (notto be confused with the first No&#235;l).</p><p>By the way, the line numbers are not part of the program, any otherresemblances to BASIC notwithstanding.<blockquote><pre class="programlisting"> 1 #!/usr/bin/perl 2 3 open(GRADES, "grades") or die "Can't open grades: $!\n"; 4 while ($line = <GRADES>) { 5 ($student, $grade) = split(" ", $line); 6 $grades{$student} .= $grade . " "; 7 } 8 9 foreach $student (sort keys %grades) {10 $scores = 0;11 $total = 0; 12 @grades = split(" ", $grades{$student});13 foreach $grade (@grades) {14 $total += $grade;15 $scores++;16 }17 $average = $total / $scores;18 print "$student: $grades{$student}\tAverage: $average\n";19 }</pre></blockquote>Now before your eyes cross permanently, we'd better point out that thisexample demonstrates a lot of what we've covered so far, plus quite abit more that we'll explain presently. But if you let your eyes go justa little out of focus, you may start to see some interesting patterns.Take some wild guesses now as to what's going on, and then later onwe'll tell you if you're right.</p><p>We'd tell you to try running it, but you may not know how yet.</p><h3 class="sect2">1.3.1. How to Do It</h3><p><a name="INDEX-150"></a><a name="INDEX-151"></a><a name="INDEX-152"></a>Gee, right about now you're probably wondering how to run a Perlprogram. The short answer is that you feed it to the Perl languageinterpreter program, which coincidentally happens to be named<em class="emphasis">perl</em>. The long answer starts out like this:There's More Than One Way To Do It.<a href="#FOOTNOTE-10">[10]</a></p><blockquote class="footnote"><a name="FOOTNOTE-10"></a><p>[10] That's the Perl Slogan,and you'll get tired of hearing it, unless you're the Local Expert, inwhich case you'll get tired of saying it. Sometimes it's shortened toTMTOWTDI, pronounced "tim-toady". But you can pronounce it however youlike. After all, TMTOWTDI.</p></blockquote><p><a name="INDEX-153"></a><a name="INDEX-154"></a><a name="INDEX-155"></a><a name="INDEX-156"></a>The first way to invoke <em class="emphasis">perl</em> (and the way most likelyto work on any operating system) is to simply call <em class="emphasis">perl</em>explicitly from the command line.<a href="#FOOTNOTE-11">[11]</a> If you are doing somethingfairly simple,you can use the <tt class="userinput"><b>-e</b></tt> switch (<tt class="literal">%</tt>in the following example represents a standard shell prompt, so don'ttype it). On Unix, you might type:<blockquote><pre class="programlisting">% <tt class="userinput"><b>perl -e 'print "Hello, world!\n";'</b></tt></pre></blockquote><a name="INDEX-157"></a></p><blockquote class="footnote"><a name="FOOTNOTE-11"></a><p>[11] Assuming that youroperating system provides a command-line interface. If you're running anolder Mac, you might need to upgrade to a version of BSD such asMac OS X.</p></blockquote><p>On other operating systems, you may have to fiddle with the quotes some.But the basic principle is the same: you're trying to cram everythingPerl needs to know into 80 columns or so.<a href="#FOOTNOTE-12">[12]</a></p><blockquote class="footnote"><a name="FOOTNOTE-12"></a><p>[12] These types ofscripts are often referred to as "one-liners". If you ever end uphanging out with other Perl programmers, you'll find that some of us arequite fond of creating intricate one-liners. Perl has occasionally beenmaligned as a write-only language because of theseshenanigans.</p></blockquote><p><a name="INDEX-158"></a>For longer scripts, you can use your favorite text editor (or any othertext editor) to put all your commands into a file and then, presumingyou named the script <em class="emphasis">gradation</em> (not to be confused with graduation),you'd say:<blockquote><pre class="programlisting">% <tt class="userinput"><b>perl gradation</b></tt></pre></blockquote>You're still invoking the Perl interpreter explicitly, but at least youdon't have to put everything on the command line every time. And youno longer have to fiddle with quotes to keep the shell happy.</p><p><a name="INDEX-159"></a><a name="INDEX-160"></a><a name="INDEX-161"></a>The most convenient way to invoke a script is just to name it directly(or click on it), and let the operating system find the interpreter foryou. On some systems, there may be ways of associating various fileextensions or directories with a particular application. On thosesystems, you should do whatever it is you do to associate the Perlscript with the <em class="emphasis">perl</em> interpreter. On Unix systemsthat support the <tt class="literal">#!</tt> "shebang" notation (and most Unixsystems do, nowadays), you can make the first line of your script be magical,so the operating system will know which program to run. Put a lineresembling line 1 of our example into your program:<blockquote><pre class="programlisting">#!/usr/bin/perl</pre></blockquote>(If <em class="emphasis">perl</em> isn't in <em class="emphasis">/usr/bin</em>, you'll have to change the <tt class="literal">#!</tt> lineaccordingly.) Then all you have to say is:<blockquote><pre class="programlisting">% <tt class="userinput"><b>gradation</b></tt></pre></blockquote><a name="INDEX-162"></a><a name="INDEX-163"></a>Of course, this didn't work because you forgot to make sure the scriptwas executable (see the manpage for <em class="emphasis">chmod</em>(1))and in your PATH. If it isn't in your PATH,you'll have to provide a complete filename so that the operating systemknows how to find your script. Something like:<blockquote><pre class="programlisting">% <tt class="userinput"><b>/home/sharon/bin/gradation</b></tt></pre></blockquote>Finally, if you are unfortunate enough to be on an ancient Unix systemthat doesn't support the magic <tt class="literal">#!</tt> line, or if thepath to your interpreter is longer than 32 characters(a built-in limit on many systems), you may be able to work around itlike this:<blockquote><pre class="programlisting">#!/bin/sh -- # perl, to stop loopingeval 'exec /usr/bin/perl -S $0 ${1+"$@"}' if 0;</pre></blockquote>Some operating systems may require variants of this to deal with<em class="emphasis">/bin/csh</em>, <em class="emphasis">DCL</em>, <em class="emphasis">COMMAND.COM</em>, or whatever happens to be yourdefault command interpreter. Ask your Local Expert.</p><p>Throughout this book, we'll just use <tt class="literal">#!/usr/bin/perl</tt> to represent allthese notions and notations, but you'll know what we really mean by it.</p><p><a name="INDEX-164"></a><a name="INDEX-165"></a>A random clue: when you write a test script, don't call your script<em class="emphasis">test</em>. Unix systems have a built-in <em class="emphasis">test</em> command, which will likelybe executed instead of your script. Try <em class="emphasis">try</em> instead.</p><p><a name="INDEX-166"></a><a name="INDEX-167"></a><a name="INDEX-168"></a>A not-so-random clue: while learning Perl, and even after you think youknow what you're doing, we suggest using the <tt class="userinput"><b>-w</b></tt>switch, especially during development. This option will turn on all sortsof useful andinteresting warning messages, not necessarily in that order. You can putthe <tt class="userinput"><b>-w</b></tt> switch on the shebang line, like this:<blockquote><pre class="programlisting">#!/usr/bin/perl -w</pre></blockquote>Now that you know how to run your own Perl program (not to be confusedwith the <em class="emphasis">perl</em> program), let's get back to our example.</p><!-- BOTTOM NAV BAR --><hr width="515" align="left"><div class="navbar"><table width="515" border="0"><tr><td align="left" valign="top" width="172"><a href="ch01_02.htm"><img src="../gifs/txtpreva.gif" alt="Previous" border="0"></a></td><td align="center" valign="top" width="171"><a href="index.htm"><img src="../gifs/txthome.gif" alt="Home" border="0"></a></td><td align="right" valign="top" width="172"><a href="ch01_04.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr><tr><td align="left" valign="top" width="172">1.2. Natural and Artificial Languages</td><td align="center" valign="top" width="171"><a href="index/index.htm"><img src="../gifs/index.gif" alt="Book Index" border="0"></a></td><td align="right" valign="top" width="172">1.4. Filehandles</td></tr></table></div><hr width="515" align="left"><!-- LIBRARY NAV BAR --><img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p><font size="-1"><a href="copyrght.htm">Copyright © 2001</a> O'Reilly & Associates. All rights reserved.</font></p><map name="library-map"> <area shape="rect" coords="2,-1,79,99" href="../index.htm"><area shape="rect" coords="84,1,157,108" href="../perlnut/index.htm"><area shape="rect" coords="162,2,248,125" href="../prog/index.htm"><area shape="rect" coords="253,2,326,130" href="../advprog/index.htm"><area shape="rect" coords="332,1,407,112" href="../cookbook/index.htm"><area shape="rect" coords="414,2,523,103" href="../sysadmin/index.htm"></map><!-- END OF BODY --></body></html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -