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

📄 ch07_01.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
📖 第 1 页 / 共 2 页
字号:
<HTML><HEAD><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen &amp; Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly &amp; Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:35:15Z"><METANAME="DC.type"CONTENT="Text.Monograph"><METANAME="DC.format"CONTENT="text/html"SCHEME="MIME"><METANAME="DC.source"CONTENT="1-56592-243-3"SCHEME="ISBN"><METANAME="DC.language"CONTENT="en-US"><METANAME="generator"CONTENT="Jade 1.1/O'Reilly DocBook 3.0 to HTML 4.0"><LINKREV="made"HREF="mailto:online-books@oreilly.com"TITLE="Online Books Comments"><LINKREL="up"HREF="index.htm"TITLE="Perl Cookbook"><LINKREL="prev"HREF="ch06_24.htm"TITLE="6.23. Regular Expression Grabbag"><LINKREL="next"HREF="ch07_02.htm"TITLE="7.1. Opening a File"></HEAD><BODYBGCOLOR="#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="Perl Cookbook"><area shape="rect" coords="629,-11,726,25" href="jobjects/fsearch.htm" alt="Search this book" /></map><div class="navbar"><p><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch06_24.htm"TITLE="6.23. Regular Expression Grabbag"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 6.23. Regular Expression Grabbag"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch07_02.htm"TITLE="7.1. Opening a File"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 7.1. Opening a File"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="chapter"><H1CLASS="chapter"><ACLASS="title"NAME="ch07-24448">7. File Access</A></H1><DIVCLASS="htmltoc"><P><B>Contents:</B><BR><ACLASS="sect1"HREF="#ch07-36590"TITLE="7.0. Introduction">Introduction</A><BR><ACLASS="sect1"HREF="ch07_02.htm"TITLE="7.1. Opening a File">Opening a File</A><BR><ACLASS="sect1"HREF="ch07_03.htm"TITLE="7.2. Opening Files with Unusual Filenames">Opening Files with Unusual Filenames</A><BR><ACLASS="sect1"HREF="ch07_04.htm"TITLE="7.3. Expanding Tildes in Filenames">Expanding Tildes in Filenames</A><BR><ACLASS="sect1"HREF="ch07_05.htm"TITLE="7.4. Making Perl Report Filenames in Errors">Making Perl Report Filenames in Errors</A><BR><ACLASS="sect1"HREF="ch07_06.htm"TITLE="7.5. Creating Temporary Files">Creating Temporary Files</A><BR><ACLASS="sect1"HREF="ch07_07.htm"TITLE="7.6. Storing Files Inside Your Program Text">Storing Files Inside Your Program Text</A><BR><ACLASS="sect1"HREF="ch07_08.htm"TITLE="7.7. Writing a Filter">Writing a Filter</A><BR><ACLASS="sect1"HREF="ch07_09.htm"TITLE="7.8. Modifying a File in Place with Temporary File">Modifying a File in Place with Temporary File</A><BR><ACLASS="sect1"HREF="ch07_10.htm"TITLE="7.9. Modifying a File in Place with -i Switch">Modifying a File in Place with -i Switch</A><BR><ACLASS="sect1"HREF="ch07_11.htm"TITLE="7.10. Modifying a File in Place Without a Temporary File">Modifying a File in Place Without a Temporary File</A><BR><ACLASS="sect1"HREF="ch07_12.htm"TITLE="7.11. Locking a File">Locking a File</A><BR><ACLASS="sect1"HREF="ch07_13.htm"TITLE="7.12. Flushing Output">Flushing Output</A><BR><ACLASS="sect1"HREF="ch07_14.htm"TITLE="7.13. Reading from Many Filehandles Without Blocking">Reading from Many Filehandles Without Blocking</A><BR><ACLASS="sect1"HREF="ch07_15.htm"TITLE="7.14. Doing Non-Blocking I/O">Doing Non-Blocking I/O</A><BR><ACLASS="sect1"HREF="ch07_16.htm"TITLE="7.15. Determining the Number of Bytes to Read">Determining the Number of Bytes to Read</A><BR><ACLASS="sect1"HREF="ch07_17.htm"TITLE="7.16. Storing Filehandles in Variables">Storing Filehandles in Variables</A><BR><ACLASS="sect1"HREF="ch07_18.htm"TITLE="7.17. Caching Open Output Filehandles">Caching Open Output Filehandles</A><BR><ACLASS="sect1"HREF="ch07_19.htm"TITLE="7.18. Printing to Many Filehandles Simultaneously">Printing to Many Filehandles Simultaneously</A><BR><ACLASS="sect1"HREF="ch07_20.htm"TITLE="7.19. Opening and Closing File Descriptors by Number">Opening and Closing File Descriptors by Number</A><BR><ACLASS="sect1"HREF="ch07_21.htm"TITLE="7.20. Copying Filehandles">Copying Filehandles</A><BR><ACLASS="sect1"HREF="ch07_22.htm"TITLE="7.21. Program: netlock">Program: netlock</A><BR><ACLASS="sect1"HREF="ch07_23.htm"TITLE="7.22. Program: lockarea">Program: lockarea</A></P><P></P></DIV><DIVCLASS="epigraph"ALIGN="right"><PCLASS="para"ALIGN="right"><I>I the heir of all the ages, in the foremost files of time.</I></P><PCLASS="attribution"ALIGN="right">-&nbsp;Alfred, Lord Tennyson <CITECLASS="citetitle">Locksley Hall</CITE></P></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch07-36590">7.0. Introduction</A></H2><PCLASS="para"><ACLASS="indexterm"NAME="ch07-idx-1000009548-0"></A>Nothing is more central to data processing than the file. As with everything else in Perl, easy things are easy and hard things are possible. Common tasks (opening, reading data, writing data) use simple I/O functions and operators, whereas fancier functions do hard things like non-blocking I/O and file locking.</P><PCLASS="para">This chapter deals with the mechanics of file <EMCLASS="emphasis">access</EM>: opening a file, telling subroutines which files to work with, locking files, and so on. <ACLASS="xref"HREF="ch08_01.htm"TITLE="File Contents">Chapter 8, <CITECLASS="chapter">File Contents</CITE></A>, deals with techniques for working with the <EMCLASS="emphasis">contents</EM> of a file: reading, writing, shuffling lines, and other operations you can do once you have access to the file.</P><PCLASS="para"><ACLASS="indexterm"NAME="ch07-idx-1000009550-0"></A>Here's Perl code for printing all lines in the file <EMCLASS="emphasis">/usr/local/widgets/data</EM> that contain the word <CODECLASS="literal">&quot;blue&quot;</CODE>:</P><PRECLASS="programlisting">open(INPUT, &quot;&lt; /usr/local/widgets/data&quot;)    or die &quot;Couldn't open /usr/local/widgets/data for reading: $!\n&quot;;while (&lt;INPUT&gt;) {    print if /blue/;}close(INPUT);</PRE><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch07-chap07_getting_0">Getting a Handle on the File</A></H3><PCLASS="para"><ACLASS="indexterm"NAME="ch07-idx-1000009551-0"></A>Central to Perl's file access is the <EMCLASS="emphasis">filehandle</EM>, like INPUT in the preceding program. This is a symbol you use to represent the file when you read and write. Because filehandles aren't variables (they don't have a <CODECLASS="literal">$</CODE>, <CODECLASS="literal">@</CODE>, or <CODECLASS="literal">%</CODE> type marker on their names &nbsp;-  but they are part of Perl's symbol table just as subroutines and variables are), storing filehandles in variables and passing them to subroutines won't always work. You should use the odd-looking <ACLASS="indexterm"NAME="ch07-idx-1000009759-0"></A><ACLASS="indexterm"NAME="ch07-idx-1000009759-1"></A><ACLASS="indexterm"NAME="ch07-idx-1000009759-2"></A><CODECLASS="literal">*FH</CODE> notation, indicating a typeglob, the basic unit of Perl's symbol table:</P><PRECLASS="programlisting">$var = *STDIN;mysub($var, *LOGFILE);</PRE><PCLASS="para">When you store filehandles in variables like this, you don't use them directly. They're called <EMCLASS="emphasis">indirect filehandles</EM><ACLASS="indexterm"NAME="ch07-idx-1000009552-0"></A> because they indirectly refer to the real filehandle. Two modules, <ACLASS="indexterm"NAME="ch07-idx-1000009553-0"></A><ACLASS="indexterm"NAME="ch07-idx-1000009553-1"></A><ACLASS="indexterm"NAME="ch07-idx-1000009553-2"></A>IO::File (standard since 5.004) and FileHandle (standard since 5.000), can create anonymous filehandles.</P><PCLASS="para">When we use IO::File or IO::Handle in our examples, you could obtain identical results by using FileHandle instead, since it's now just a wrapper module.</P><PCLASS="para">Here's how we'd write the <CODECLASS="literal">&quot;blue&quot;</CODE>-finding program with the IO::File module using purely object-oriented notation:</P><PRECLASS="programlisting">use IO::File;$input = IO::File-&gt;new(&quot;&lt; /usr/local/widgets/data&quot;)    or die &quot;Couldn't open /usr/local/widgets/data for reading: $!\n&quot;;while (defined($line = $input-&gt;getline())) {    chomp($line);    STDOUT-&gt;print($line) if $line =~ /blue/;}$input-&gt;close();</PRE><PCLASS="para">As you see, it's much more readable to use filehandles directly. It's also a lot faster.</P><PCLASS="para">But here's a little secret for you: you can skip all that arrow and method-call business altogether. Unlike most objects, you don't actually <EMCLASS="emphasis">have</EM> to use IO::File objects in an object-oriented way. They're essentially just anonymous filehandles, so you can use them anywhere you'd use a regular indirect filehandle. <ACLASS="xref"HREF="ch07_17.htm"TITLE="Storing Filehandles in Variables">Recipe 7.16</A> covers these modules and the <CODECLASS="literal">*FH</CODE> notation. We use both IO::File and symbolic filehandles in this chapter.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch07-chap07_standard_0">Standard FileHandles</A></H3><PCLASS="para"><ACLASS="indexterm"NAME="ch07-idx-1000009554-0"></A><ACLASS="indexterm"NAME="ch07-idx-1000009554-1"></A><ACLASS="indexterm"NAME="ch07-idx-1000009554-2"></A><ACLASS="indexterm"NAME="ch07-idx-1000009554-3"></A>Every program starts out with three global filehandles already opened: STDIN, STDOUT, and STDERR. STDIN (<EMCLASS="emphasis">standard input</EM>) is the default source of input, STDOUT (<EMCLASS="emphasis">standard output</EM>) is the default destination for output, and STDERR (<EMCLASS="emphasis">standard error</EM>) is the default place to send warnings and errors. For interactive programs, STDIN is the keyboard, STDOUT and STDERR are the screen:</P><PRECLASS="programlisting">while (&lt;STDIN&gt;) {                   # reads from STDIN    unless (/\d/) {        warn &quot;No digit found.\n&quot;;   # writes to STDERR    }    print &quot;Read: &quot;, $_;             # writes to STDOUT}END { close(STDOUT)                 or die &quot;couldn't close STDOUT: $!&quot; }</PRE><PCLASS="para">Filehandles live in packages. That way, two packages can have filehandles with the same name and be separate, just as they can with subroutines and variables. The <CODECLASS="literal">open</CODE><ACLASS="indexterm"NAME="ch07-idx-1000009564-0"></A><ACLASS="indexterm"NAME="ch07-idx-1000009564-1"></A> function associates a filehandle with a file or program, after which you use that filehandle for I/O. When done, <CODECLASS="literal">close</CODE> the filehandle to break the association.</P><PCLASS="para">Files are accessed at the operating system through numeric file descriptors. You can learn a filehandle's descriptor number using the <CODECLASS="literal">fileno</CODE> function. Perl's filehandles are sufficient for most file operations, but <ACLASS="xref"HREF="ch07_20.htm"TITLE="Opening and Closing File Descriptors by Number">Recipe 7.19</A> tells you how to deal with the situation where you're given an file descriptor and want to turn it into a filehandle you can use.<ACLASS="indexterm"NAME="ch07-idx-1000009556-0"></A><ACLASS="indexterm"NAME="ch07-idx-1000009556-1"></A><ACLASS="indexterm"NAME="ch07-idx-1000009556-2"></A><ACLASS="indexterm"NAME="ch07-idx-1000009556-3"></A></P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch07-chap07_i_o_0">I/O Operations</A></H3><PCLASS="para"><ACLASS="indexterm"NAME="ch07-idx-1000009566-0"></A>Perl's most common operations for file interaction are <CODECLASS="literal">open</CODE>, <CODECLASS="literal">print</CODE>, <CODECLASS="literal">&lt;FH&gt;</CODE> to read a record, and <CODECLASS="literal">close</CODE>. These are wrappers around routines from the C buffered input/output library called <EMCLASS="emphasis">stdio</EM><ACLASS="indexterm"NAME="ch07-idx-1000009565-0"></A>. Perl's I/O functions are documented in <ACLASS="olink"HREF="../prog/ch03_01.htm">Chapter 3</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A>, <ICLASS="filename">perlfunc </I>(1), and your system's <ICLASS="filename">stdio </I>(3S) manpages. The next chapter details I/O operations like &lt;&gt;, <CODECLASS="literal">print</CODE>, <CODECLASS="literal">seek</CODE>, and <CODECLASS="literal">tell</CODE>.</P><PCLASS="para">The most important I/O function is <CODECLASS="literal">open</CODE>. It takes two arguments, the filehandle and a string containing the filename and <ACLASS="indexterm"NAME="ch07-idx-1000009573-0"></A><ACLASS="indexterm"NAME="ch07-idx-1000009573-1"></A><ACLASS="indexterm"NAME="ch07-idx-1000009573-2"></A><ACLASS="indexterm"NAME="ch07-idx-1000009573-3"></A><A

⌨️ 快捷键说明

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