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

📄 ch01_04.htm

📁 编程珍珠,里面很多好用的代码,大家可以参考学习呵呵,
💻 HTM
字号:
<html><head><title>Filehandles (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="Filehandles"><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_03.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_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">1.4. Filehandles</h2><p><a name="INDEX-169"></a><a name="INDEX-170"></a><a name="INDEX-171"></a><a name="INDEX-172"></a>Unless you're using artificial intelligence to model a solipsisticphilosopher, your program needs some way to communicate with theoutside world.  In lines 3 and 4 of our Average Exampleyou'll see the word <tt class="literal">GRADES</tt>, which exemplifiesanother of Perl's data types, the <em class="emphasis">filehandle</em>.  A filehandle is justa name you give to a file, device, socket, or pipe to help you rememberwhich one you're talking about, and to hide some of the complexities ofbuffering and such.  (Internally, filehandles are similar to streamsfrom a language like C++ or I/O channels from BASIC.)</p><p><a name="INDEX-173"></a>Filehandles make it easier for you to get input from and send output tomany different places.  Part of what makes Perl a good glue language isthat it can talk to many files and processes at once.  Having nicesymbolic names for various external objects is just part of being a goodglue language.<a href="#FOOTNOTE-13">[13]</a></p><blockquote class="footnote"><a name="FOOTNOTE-13"></a><p>[13] Some of the other things that make Perl a goodglue language are: it's 8-bit clean, it's embeddable, and you can embedother things in it via extension modules.  It's concise, and it "networks"easily.  It's environmentally conscious, so to speak.  You can invoke itin many different ways (as we saw earlier).  But most of all, thelanguage itself is not so rigidly structured that you can't get it to"flow" around your problem.  It comes back to that TMTOWTDI thingagain.</p></blockquote><p><a name="INDEX-174"></a><a name="INDEX-175"></a><a name="INDEX-176"></a><a name="INDEX-177"></a>You create a filehandle and attach it to a file by using<tt class="literal">open</tt>.  The <tt class="literal">open</tt> function takes atleast two parameters: the filehandle and filename you want to associateit with.  Perl also gives you some predefined (and preopened)filehandles.  <tt class="literal">STDIN</tt> is your program'snormal input channel, while <tt class="literal">STDOUT</tt> is your program's normal outputchannel.  And <tt class="literal">STDERR</tt> is an additional output channel that allows yourprogram to make snide remarks off to the side while it transforms (orattempts to transform) your input into your output.<a href="#FOOTNOTE-14">[14]</a><a name="INDEX-178"></a><a name="INDEX-179"></a></p><blockquote class="footnote"><a name="FOOTNOTE-14"></a><p>[14] Thesefilehandles are typically attached to your terminal, so you can type toyour program and see its output, but they may also be attached to files(and such).  Perl can give you these predefined handles because youroperating system already provides them, one way or another.  UnderUnix, processes inherit standard input, output, and error from theirparent process, typically a shell.  One of the duties of a shell is toset up these I/O streams so that the child process doesn't need toworry about them.</p></blockquote><p>Since you can use the <tt class="literal">open</tt> function to create filehandles for variouspurposes (input, output, piping), you need to be able to specify whichbehavior you want.  As you might do on the command line, you simplyadd characters to the filename.<blockquote><pre class="programlisting">open(SESAME, "filename")               # read from existing fileopen(SESAME, "&lt;filename")              #   (same thing, explicitly)open(SESAME, "&gt;filename")              # create file and write to itopen(SESAME, "&gt;&gt;filename")             # append to existing fileopen(SESAME, "| output-pipe-command")  # set up an output filteropen(SESAME, "input-pipe-command |")   # set up an input filter</pre></blockquote>As you can see, the name you pick for the filehandle isarbitrary. Once opened, the filehandle <tt class="literal">SESAME</tt> canbe used to access the file or pipe until it is explicitly closed(with, you guessed it, <tt class="literal">close(SESAME)</tt>), or until thefilehandle is attached to another file by a subsequent<tt class="literal">open</tt> on the same filehandle.<a href="#FOOTNOTE-15">[15]</a></p><blockquote class="footnote"><a name="FOOTNOTE-15"></a><p>[15]Opening an already opened filehandle implicitly closes the first file,making it inaccessible to the filehandle, and opens a differentfile.  You must be careful that this is what you really want todo.  Sometimes it happens accidentally, like when you say<tt class="literal">open($handle,$file)</tt>, and <tt class="literal">$handle</tt>happens to contain a constant string.  Be sure to set<tt class="literal">$handle</tt> to something unique, or you'll just open anew file on the same filehandle.  Or you can leave <tt class="literal">$handle</tt>undefined, and Perl will fill it in for you.</p></blockquote><p><a name="INDEX-180"></a><a name="INDEX-181"></a><a name="INDEX-182"></a><a name="INDEX-183"></a><a name="INDEX-184"></a>Once you've opened a filehandle for input, you can read a line usingthe line reading operator,<tt class="literal">&lt;</tt><tt class="literal">&gt;</tt>.  This is also known asthe angle operator because it's made of angle brackets.  The angleoperator encloses the filehandle (<tt class="literal">&lt;SESAME&gt;</tt>)you want to read lines from.  The empty angle operator,<tt class="literal">&lt;&gt;</tt>, will read lines from all the filesspecified on the command line, or <tt class="literal">STDIN</tt>, if nonewere specified.  (This is standard behavior for many filter programs.)An example using the <tt class="literal">STDIN</tt> filehandle to read ananswer supplied by the user would look something like this:<blockquote><pre class="programlisting">print STDOUT "Enter a number: ";          # ask for a number$number = &lt;STDIN&gt;;                        # input the numberprint STDOUT "The number is $number.\n";  # print the number</pre></blockquote><a name="INDEX-185"></a><a name="INDEX-186"></a>Did you see what we just slipped by you?  What's that<tt class="literal">STDOUT</tt> doing there in those <tt class="literal">print</tt>statements?  Well, that's just one of the ways you can use an outputfilehandle.  A filehandle may be supplied as the first argument tothe <tt class="literal">print</tt> statement, and if present, tells theoutput where to go.  In this case, the filehandle is redundant, becausethe output would have gone to <tt class="literal">STDOUT</tt> anyway.  Much as<tt class="literal">STDIN</tt> is the default for input, <tt class="literal">STDOUT</tt>is the default for output.  (In line 18 of our Average Example, we leftit out to avoid confusing you up till now.)</p><p><a name="INDEX-187"></a><a name="INDEX-188"></a><a name="INDEX-189"></a>If you try the previous example,you may notice that you get an extra blank line.  This happens becausethe line-reading operation does not automatically remove the newlinefrom your input line (your input would be, for example, "<tt class="literal">9\n</tt>").  Forthose times when you do want to remove the newline, Perl provides the<tt class="literal">chop</tt> and <tt class="literal">chomp</tt> functions.  <tt class="literal">chop</tt> will indiscriminately remove(and return) the last character of the string, while <tt class="literal">chomp</tt> will onlyremove the end of record marker (generally, "<tt class="literal">\n</tt>") and return thenumber of characters so removed.  You'll often see this idiom forinputting a single line:<blockquote><pre class="programlisting">chop($number = &lt;STDIN&gt;);    # input number and remove newline</pre></blockquote>which means the same thing as:<blockquote><pre class="programlisting">$number = &lt;STDIN&gt;;          # input numberchop($number);              # remove newline</pre></blockquote></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_03.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_05.htm"><img src="../gifs/txtnexta.gif" alt="Next" border="0"></a></td></tr><tr><td align="left" valign="top" width="172">1.3. An Average Example</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.5. Operators</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 &copy; 2001</a> O'Reilly &amp; 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 + -