📄 ch09_07.htm
字号:
<HTML><HEAD><TITLE>Recipe 9.6. Globbing, or Getting a List of Filenames Matching a Pattern (Perl Cookbook)</TITLE><METANAME="DC.title"CONTENT="Perl Cookbook"><METANAME="DC.creator"CONTENT="Tom Christiansen & Nathan Torkington"><METANAME="DC.publisher"CONTENT="O'Reilly & Associates, Inc."><METANAME="DC.date"CONTENT="1999-07-02T01:39:13Z"><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_06.htm"TITLE="9.5. Processing All Files in a Directory"><LINKREL="next"HREF="ch09_08.htm"TITLE="9.7. Processing All Files in a Directory Recursively"></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_06.htm"TITLE="9.5. Processing All Files in a Directory"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 9.5. Processing All Files in a Directory"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_08.htm"TITLE="9.7. Processing All Files in a Directory Recursively"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 9.7. Processing All Files in a Directory Recursively"BORDER="0"></A></TD></TR></TABLE></DIV><DIVCLASS="sect1"><H2CLASS="sect1"><ACLASS="title"NAME="ch09-27581">9.6. Globbing, or Getting a List of Filenames Matching a Pattern</A></H2><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch09-pgfId-634">Problem<ACLASS="indexterm"NAME="ch09-idx-1000004390-0"></A><ACLASS="indexterm"NAME="ch09-idx-1000004390-1"></A><ACLASS="indexterm"NAME="ch09-idx-1000004390-2"></A></A></H3><PCLASS="para">You want to get a list of filenames similar to MS-DOS's <CODECLASS="literal">*.*</CODE> and Unix's <CODECLASS="literal">*.h</CODE> (this is called <EMCLASS="emphasis">globbing</EM>).</P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch09-pgfId-640">Solution</A></H3><PCLASS="para">Perl provides globbing with the semantics of the Unix C shell through the <CODECLASS="literal">glob</CODE><ACLASS="indexterm"NAME="ch09-idx-1000004391-0"></A><ACLASS="indexterm"NAME="ch09-idx-1000004391-1"></A> keyword and < >:</P><PRECLASS="programlisting">@list = <*.c>;@list = glob("*.c");</PRE><PCLASS="para">You can also use <CODECLASS="literal">readdir</CODE> to extract the filenames manually:</P><PRECLASS="programlisting">opendir(DIR, $path);@files = grep { /\.c$/ } readdir(DIR);closedir(DIR);</PRE><PCLASS="para">The CPAN module File::KGlob does globbing without length limits:</P><PRECLASS="programlisting">use File::KGlob;@files = glob("*.c");</PRE></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch09-pgfId-666">Discussion</A></H3><PCLASS="para">Perl's built-in <CODECLASS="literal">glob</CODE> and <WILDCARD> notation (not to be confused with <FILEHANDLE>) currently use an external program to get the list of filenames on most platforms. This program is <EMCLASS="emphasis">csh</EM> on Unix,[<ACLASS="footnote"HREF="#ch09-pgfId-1000000674">2</A>] and a program called <EMCLASS="emphasis">dosglob.exe</EM> on Windows. On VMS and the Macintosh, file globs are done internally without an external program. Globs are supposed to give C shell semantics on non-Unix systems to encourage portability. The use of the shell on Unix also makes this inappropriate for setuid scripts.</P><BLOCKQUOTECLASS="footnote"><DIVCLASS="footnote"><PCLASS="para"><ACLASS="footnote"NAME="ch09-pgfId-1000000674">[2]</A> Usually. If <EMCLASS="emphasis">tcsh</EM> is installed, Perl uses that because it's safer. If neither is installed, <EMCLASS="emphasis">/bin/sh</EM> is used.</P></DIV></BLOCKQUOTE><PCLASS="para">To get around this, you can either roll your own selection mechanism using the built-in <CODECLASS="literal">opendir</CODE><ACLASS="indexterm"NAME="ch09-idx-1000004403-0"></A> or CPAN's <ACLASS="indexterm"NAME="ch09-idx-1000004402-0"></A>File::KGlob, neither of which uses external programs. File::KGlob provides Unix shell-like globbing semantics, whereas <CODECLASS="literal">opendir</CODE> lets you select files with Perl's regular expressions.</P><PCLASS="para">At its simplest, an <CODECLASS="literal">opendir</CODE> solution uses <CODECLASS="literal">grep</CODE> to filter the list returned by <CODECLASS="literal">readdir</CODE>:</P><PRECLASS="programlisting">@files = grep { /\.[ch]$/i } readdir(DH);</PRE><PCLASS="para">You could also do this with the DirHandle module:</P><PRECLASS="programlisting">use DirHandle;$dh = DirHandle->new($path) or die "Can't open $path : $!\n";@files = grep { /\.[ch]$/i } $dh->read();</PRE><PCLASS="para">As always, the filenames returned don't include the directory. When you use the filename, you'll need to prepend the directory name:</P><PRECLASS="programlisting">opendir(DH, $dir) or die "Couldn't open $dir for reading: $!";@files = ();while( defined ($file = readdir(DH)) ) { next unless /\.[ch]$/i; my $filename = "$dir/$file"; push(@files, $filename) if -T $file;}</PRE><PCLASS="para">The following example combines directory reading and filtering with the Schwartzian Transform from <ACLASS="xref"HREF="ch04_01.htm"TITLE="Arrays">Chapter 4, <CITECLASS="chapter">Arrays</CITE></A>, for efficiency. It sets <CODECLASS="literal">@dirs</CODE> to a sorted list of the subdirectories in a directory whose names are all numeric:</P><PRECLASS="programlisting">@dirs = map { $_->[1] } # extract pathnames sort { $a->[0] <=> $b->[0] } # sort names numeric grep { -d $_->[1] } # path is a dir map { [ $_, "$path/$_" ] } # form (name, path) grep { /^\d+$/ } # just numerics readdir(DIR); # all files</PRE><PCLASS="para"><ACLASS="xref"HREF="ch04_16.htm"TITLE="Sorting a List by Computable Field">Recipe 4.15</A> explains how to read these strange-looking constructs. As always, formatting and documenting your code can make it much easier to read and <CODECLASS="literal"></CODE><ACLASS="indexterm"NAME="ch09-idx-1000004398-0"></A><ACLASS="indexterm"NAME="ch09-idx-1000004398-1"></A>understand.<ACLASS="indexterm"NAME="ch09-idx-1000004393-0"></A><ACLASS="indexterm"NAME="ch09-idx-1000004393-1"></A></P></DIV><DIVCLASS="sect2"><H3CLASS="sect2"><ACLASS="title"NAME="ch09-pgfId-724">See Also</A></H3><PCLASS="para">The <CODECLASS="literal">opendir</CODE>, <CODECLASS="literal">readdir</CODE>, <CODECLASS="literal">closedir</CODE>, <CODECLASS="literal">grep</CODE>, <CODECLASS="literal">map</CODE>, and <CODECLASS="literal">sort</CODE> functions in <ICLASS="filename">perlfunc</I> (1) and 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>; documentation for the standard DirHandle module (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>); the "I/O Operators" section of <ICLASS="filename">perlop </I>(1), and the <ACLASS="olink"HREF="../prog/ch02_03.htm#PERL2-CH-2-SECT-3.7.3">"Filename Globbing Operator"</A> section of <ACLASS="olink"HREF="../prog/ch02_01.htm">Chapter 2</A> of <ACLASS="citetitle"HREF="../prog/index.htm"TITLE="Programming Perl"><CITECLASS="citetitle">Programming Perl</CITE></A>; we talk more about globbing in <ACLASS="xref"HREF="ch06_10.htm"TITLE="Matching Shell Globs as Regular Expressions">Recipe 6.9</A>; <ACLASS="xref"HREF="ch09_08.htm"TITLE="Processing All Files in a Directory Recursively">Recipe 9.7</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_06.htm"TITLE="9.5. Processing All Files in a Directory"><IMGSRC="../gifs/txtpreva.gif"ALT="Previous: 9.5. Processing All Files in a Directory"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_08.htm"TITLE="9.7. Processing All Files in a Directory Recursively"><IMGSRC="../gifs/txtnexta.gif"ALT="Next: 9.7. Processing All Files in a Directory Recursively"BORDER="0"></A></TD></TR><TR><TDALIGN="LEFT"VALIGN="TOP"WIDTH="228">9.5. Processing All Files in a Directory</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.7. Processing All Files in a Directory Recursively</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 © 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 + -