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

📄 ch09_08.htm

📁 By Tom Christiansen and Nathan Torkington ISBN 1-56592-243-3 First Edition, published August 1998
💻 HTM
字号:
<HTML><HEAD><TITLE>Recipe 9.7. Processing All Files in a Directory Recursively (Perl Cookbook)</TITLE><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:39:18Z"><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="ch09_01.htm"TITLE="9. Directories"><LINKREL="prev"HREF="ch09_07.htm"TITLE="9.6. Globbing, or Getting a List of Filenames Matching a Pattern"><LINKREL="next"HREF="ch09_09.htm"TITLE="9.8. Removing a Directory and Its Contents"></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="ch09_07.htm"TITLE="9.6. Globbing, or Getting a List of Filenames Matching a Pattern"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 9.6. Globbing, or Getting a List of Filenames Matching a Pattern"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><B><FONTFACE="ARIEL,HELVETICA,HELV,SANSERIF"SIZE="-1"><ACLASS="chapter"REL="up"HREF="ch09_01.htm"TITLE="9. Directories"></A></FONT></B></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch09_09.htm"TITLE="9.8. Removing a Directory and Its Contents"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 9.8. Removing a Directory and Its Contents"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch09-11236">9.7. Processing All Files in a Directory Recursively</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch09-pgfId-734">Problem<ACLASS="indexterm"NAME="ch09-idx-1000004404-0"></A><ACLASS="indexterm"NAME="ch09-idx-1000004404-1"></A><ACLASS="indexterm"NAME="ch09-idx-1000004404-2"></A></A></H3><PCLASS="para">You want to do something to each file and subdirectory in a particular directory.</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch09-pgfId-740">Solution</A></H3><PCLASS="para">Use the standard <ACLASS="indexterm"NAME="ch09-idx-1000004418-0"></A>File::Find module.</P><PRECLASS="programlisting">use File::Find;sub process_file {    # do whatever;}find(\&amp;process_file, @DIRLIST);</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch09-pgfId-756">Discussion</A></H3><PCLASS="para">File::Find provides a convenient way to process a directory recursively. It does the directory scans and recursion for you. All you do is pass <CODECLASS="literal">find</CODE> a code reference and a list of directories. For each file in those directories, recursively, <CODECLASS="literal">find</CODE> calls your function.</P><PCLASS="para">Before calling your function, <CODECLASS="literal">find</CODE> changes to the directory being visited, whose path relative to the starting directory is stored in the <CODECLASS="literal">$File::Find::dir</CODE> variable. <CODECLASS="literal">$_</CODE> is set to the basename of the file being visited, and the full path of that file can be found in <CODECLASS="literal">$File::Find::name</CODE>. Your code can set <CODECLASS="literal">$File::Find::prune</CODE> to true to tell <CODECLASS="literal">find</CODE> not to descend into the directory just seen.</P><PCLASS="para">This simple example demonstrates File::Find. We give <CODECLASS="literal">find</CODE> an anonymous subroutine that prints the name of each file visited and adds a <CODECLASS="literal">/</CODE> to the names of directories:</P><PRECLASS="programlisting">@ARGV = qw(.) unless @ARGV;use File::Find;find sub { print $File::Find::name, -d &amp;&amp; '/', &quot;\n&quot; }, @ARGV;</PRE><PCLASS="para">This prints a <CODECLASS="literal">/</CODE> after directory names using the <BCLASS="emphasis.bold">-d</B> file test operator, which returns the empty string <CODECLASS="literal">''</CODE> if it fails.</P><PCLASS="para">The following program prints the sum of everything in a directory. It gives <CODECLASS="literal">find</CODE> an anonymous subroutine to keep a running sum of the sizes of each file it visits. That includes all inode types, including the sizes of directories and symbolic links, not just regular files. Once the <CODECLASS="literal">find</CODE> function returns, the accumulated sum is displayed.</P><PRECLASS="programlisting">use File::Find;@ARGV = ('.') unless @ARGV;my $sum = 0;find sub { $sum += -s }, @ARGV;print &quot;@ARGV contains $sum bytes\n&quot;;</PRE><PCLASS="para">This code finds the largest single file within a set of directories:</P><PRECLASS="programlisting">use File::Find;@ARGV = ('.') unless @ARGV;my ($saved_size, $saved_name) = (-1, '');sub biggest {    return unless -f &amp;&amp; -s _ &gt; $saved_size;    $saved_size = -s _;    $saved_name = $File::Find::name;}find(\&amp;biggest, @ARGV);print &quot;Biggest file $saved_name in @ARGV is $saved_size bytes long.\n&quot;;</PRE><PCLASS="para">We use <CODECLASS="literal">$saved_size</CODE> and <CODECLASS="literal">$saved_name</CODE> to keep track of the name and the size of the largest file visited. If we find a file bigger than the largest seen so far, we replace the saved name and size with the current ones. When the <CODECLASS="literal">find</CODE> is done running, the largest file and its size are printed out, rather verbosely. A more general tool would probably just print the filename, its size, or both. This time we used a named function rather than an anonymous one because the function was getting big.</P><PCLASS="para">It's simple to change this to find the most recently changed file:</P><PRECLASS="programlisting">use File::Find;@ARGV = ('.') unless @ARGV;my ($age, $name);sub youngest {    return if defined $age &amp;&amp; $age &gt; (stat($_))[9];    $age = (stat(_))[9];    $name = $File::Find::name;}find(\&amp;youngest, @ARGV);print &quot;$name &quot; . scalar(localtime($age)) . &quot;\n&quot;;</PRE><PCLASS="para">The File::Find module doesn't export its <CODECLASS="literal">$name</CODE> variable, so always refer to it by its fully qualified name. The example in <ACLASS="xref"HREF="ch09_08.htm#ch09-34586"TITLE="fdirs">Example 9.2</A> is more a demonstration of namespace munging than of recursive directory traversal, although it does find all the directories. It makes <CODECLASS="literal">$name</CODE> in our current package an alias for the one in File::Find, which is essentially how Exporter works. Then it declares its own version of <CODECLASS="literal">find</CODE> with a prototype that lets it be called like <CODECLASS="literal">grep</CODE> or <CODECLASS="literal">map</CODE>.</P><DIVCLASS="example"><H4CLASS="example"><ACLASS="title"NAME="ch09-34586">Example 9.2: fdirs</A></H4><PRECLASS="programlisting">#!/usr/bin/perl -lw# <ACLASS="indexterm"NAME="ch09-idx-1000004489-0"></A>fdirs - find all directories@ARGV = qw(.) unless @ARGV;use File::Find ();sub find(&amp;@) { &amp;File::Find::find }*name = *File::Find::name;find { print $name if -d } @ARGV;</PRE></DIV><PCLASS="para">Our <CODECLASS="literal">find</CODE> only calls the <CODECLASS="literal">find</CODE> in File::Find, which we were careful not to import by specifying an <CODECLASS="literal">()</CODE> empty list in the <CODECLASS="literal">use</CODE> statement. Rather than write this:</P><PRECLASS="programlisting">find sub { print $File::Find::name if -d }, @ARGV;</PRE><PCLASS="para">we can write the more pleasant:</P><PRECLASS="programlisting">find { print $name if -d } @ARGV;<ACLASS="indexterm"NAME="ch09-idx-1000004406-0"></A><ACLASS="indexterm"NAME="ch09-idx-1000004406-1"></A><ACLASS="indexterm"NAME="ch09-idx-1000004406-2"></A><ACLASS="indexterm"NAME="ch09-idx-1000004406-3"></A></PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch09-pgfId-856">See Also</A></H3><PCLASS="para">The documentation for the standard File::Find and Exporter modules (also in <ACLASS="olink"HREF="../prog/ch07_01.htm">Chapter 7</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A>); your system's <ICLASS="filename">find </I>(1) manpage; <ACLASS="xref"HREF="ch09_07.htm"TITLE="Globbing, or Getting a List of Filenames Matching a Pattern">Recipe 9.6</A></P></DIV></DIV><DIVCLASS="htmlnav"><P></P><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><TABLEWIDTH="684"BORDER="0"CELLSPACING="0"CELLPADDING="0"><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch09_07.htm"TITLE="9.6. Globbing, or Getting a List of Filenames Matching a Pattern"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 9.6. Globbing, or Getting a List of Filenames Matching a Pattern"BORDER="0"></A></TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="book"HREF="index.htm"TITLE="Perl Cookbook"><IMGSRC="../gifs/txthome.gif"ALT="Perl Cookbook"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228"><ACLASS="sect1"HREF="ch09_09.htm"TITLE="9.8. Removing a Directory and Its Contents"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 9.8. Removing a Directory and Its Contents"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">9.6. Globbing, or Getting a List of Filenames Matching a Pattern</TD><TDALIGN="CENTER"VALIGN="TOP"WIDTH="228"><ACLASS="index"HREF="index/index.htm"TITLE="Book Index"><IMGSRC="../gifs/index.gif"ALT="Book Index"BORDER="0"></A></TD><TDALIGN="RIGHT"VALIGN="TOP"WIDTH="228">9.8. Removing a Directory and Its Contents</TD></TR></TABLE><HRALIGN="LEFT"WIDTH="684"TITLE="footer"><FONTSIZE="-1"></DIV<!-- LIBRARY NAV BAR --> <img src="../gifs/smnavbar.gif" usemap="#library-map" border="0" alt="Library Navigation Links"><p> <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 + -