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

📄 find.pm

📁 Astercon2 开源软交换 2.2.0
💻 PM
📖 第 1 页 / 共 3 页
字号:
package File::Find;use 5.006;use strict;use warnings;use warnings::register;our $VERSION = '1.10';require Exporter;require Cwd;## Modified to ensure sub-directory traversal order is not inverded by stack# push and pops.  That is remains in the same order as in the directory file,# or user pre-processing (EG:sorted).#=head1 NAMEFile::Find - Traverse a directory tree.=head1 SYNOPSIS    use File::Find;    find(\&wanted, @directories_to_search);    sub wanted { ... }    use File::Find;    finddepth(\&wanted, @directories_to_search);    sub wanted { ... }    use File::Find;    find({ wanted => \&process, follow => 1 }, '.');=head1 DESCRIPTIONThese are functions for searching through directory trees doing workon each file found similar to the Unix I<find> command.  File::Findexports two functions, C<find> and C<finddepth>.  They work similarlybut have subtle differences.=over 4=item B<find>  find(\&wanted,  @directories);  find(\%options, @directories);C<find()> does a depth-first search over the given C<@directories> inthe order they are given.  For each file or directory found, it callsthe C<&wanted> subroutine.  (See below for details on how to use theC<&wanted> function).  Additionally, for each directory found, it willC<chdir()> into that directory and continue the search, invoking theC<&wanted> function on each file or subdirectory in the directory.=item B<finddepth>  finddepth(\&wanted,  @directories);  finddepth(\%options, @directories);C<finddepth()> works just like C<find()> except that is invokes theC<&wanted> function for a directory I<after> invoking it for thedirectory's contents.  It does a postorder traversal instead of apreorder traversal, working from the bottom of the directory tree upwhere C<find()> works from the top of the tree down.=back=head2 %optionsThe first argument to C<find()> is either a code reference to yourC<&wanted> function, or a hash reference describing the operationsto be performed for each file.  Thecode reference is described in L<The wanted function> below.Here are the possible keys for the hash:=over 3=item C<wanted>The value should be a code reference.  This code reference isdescribed in L<The wanted function> below.=item C<bydepth>Reports the name of a directory only AFTER all its entrieshave been reported.  Entry point C<finddepth()> is a shortcut forspecifying C<<{ bydepth => 1 }>> in the first argument of C<find()>.=item C<preprocess>The value should be a code reference. This code reference is used topreprocess the current directory. The name of the currently processeddirectory is in C<$File::Find::dir>. Your preprocessing function iscalled after C<readdir()>, but before the loop that calls the C<wanted()>function. It is called with a list of strings (actually file/directorynames) and is expected to return a list of strings. The code can beused to sort the file/directory names alphabetically, numerically,or to filter out directory entries based on their name alone. WhenI<follow> or I<follow_fast> are in effect, C<preprocess> is a no-op.=item C<postprocess>The value should be a code reference. It is invoked just before leavingthe currently processed directory. It is called in void context with noarguments. The name of the current directory is in C<$File::Find::dir>. Thishook is handy for summarizing a directory, such as calculating its diskusage. When I<follow> or I<follow_fast> are in effect, C<postprocess> is ano-op.=item C<follow>Causes symbolic links to be followed. Since directory trees with symboliclinks (followed) may contain files more than once and may even havecycles, a hash has to be built up with an entry for each file.This might be expensive both in space and time for a largedirectory tree. See I<follow_fast> and I<follow_skip> below.If either I<follow> or I<follow_fast> is in effect:=over 6=item *It is guaranteed that an I<lstat> has been called before the user'sC<wanted()> function is called. This enables fast file checks involving S<_>.Note that this guarantee no longer holds if I<follow> or I<follow_fast>are not set.=item *There is a variable C<$File::Find::fullname> which holds the absolutepathname of the file with all symbolic links resolved.  If the link isa dangling symbolic link, then fullname will be set to C<undef>.=backThis is a no-op on Win32.=item C<follow_fast>This is similar to I<follow> except that it may report some files morethan once.  It does detect cycles, however.  Since only symbolic linkshave to be hashed, this is much cheaper both in space and time.  Ifprocessing a file more than once (by the user's C<wanted()> function)is worse than just taking time, the option I<follow> should be used.This is also a no-op on Win32.=item C<follow_skip>C<follow_skip==1>, which is the default, causes all files which areneither directories nor symbolic links to be ignored if they are aboutto be processed a second time. If a directory or a symbolic linkare about to be processed a second time, File::Find dies.C<follow_skip==0> causes File::Find to die if any file is about to beprocessed a second time.C<follow_skip==2> causes File::Find to ignore any duplicate files anddirectories but to proceed normally otherwise.=item C<dangling_symlinks>If true and a code reference, will be called with the symbolic linkname and the directory it lives in as arguments.  Otherwise, if trueand warnings are on, warning "symbolic_link_name is a danglingsymbolic link\n" will be issued.  If false, the dangling symbolic linkwill be silently ignored.=item C<no_chdir>Does not C<chdir()> to each directory as it recurses. The C<wanted()>function will need to be aware of this, of course. In this case,C<$_> will be the same as C<$File::Find::name>.=item C<untaint>If find is used in taint-mode (-T command line switch or if EUID != UIDor if EGID != GID) then internally directory names have to be untaintedbefore they can be chdir'ed to. Therefore they are checked against a regularexpression I<untaint_pattern>.  Note that all names passed to the user'sI<wanted()> function are still tainted. If this option is used whilenot in taint-mode, C<untaint> is a no-op.=item C<untaint_pattern>See above. This should be set using the C<qr> quoting operator.The default is set to  C<qr|^([-+@\w./]+)$|>.Note that the parentheses are vital.=item C<untaint_skip>If set, a directory which fails the I<untaint_pattern> is skipped,including all its sub-directories. The default is to 'die' in such a case.=back=head2 The wanted functionThe C<wanted()> function does whatever verifications you want oneach file and directory.  Note that despite its name, the C<wanted()>function is a generic callback function, and does B<not> tellFile::Find if a file is "wanted" or not.  In fact, its return valueis ignored.The wanted function takes no arguments but rather does its workthrough a collection of variables.=over 4=item C<$File::Find::dir> is the current directory name,=item C<$_> is the current filename within that directory=item C<$File::Find::name> is the complete pathname to the file.=backDon't modify these variables.For example, when examining the file F</some/path/foo.ext> you will have:    $File::Find::dir  = /some/path/    $_                = foo.ext    $File::Find::name = /some/path/foo.extYou are chdir()'d to C<$File::Find::dir> when the function is called,unless C<no_chdir> was specified. Note that when changing todirectories is in effect the root directory (F</>) is a somewhatspecial case inasmuch as the concatenation of C<$File::Find::dir>,C<'/'> and C<$_> is not literally equal to C<$File::Find::name>. Thetable below summarizes all variants:              $File::Find::name  $File::Find::dir  $_ default      /                  /                 . no_chdir=>0  /etc               /                 etc              /etc/x             /etc              x no_chdir=>1  /                  /                 /              /etc               /                 /etc              /etc/x             /etc              /etc/xWhen <follow> or <follow_fast> are in effect, there isalso a C<$File::Find::fullname>.  The function may setC<$File::Find::prune> to prune the tree unless C<bydepth> wasspecified.  Unless C<follow> or C<follow_fast> is specified, forcompatibility reasons (find.pl, find2perl) there are in addition thefollowing globals available: C<$File::Find::topdir>,C<$File::Find::topdev>, C<$File::Find::topino>,C<$File::Find::topmode> and C<$File::Find::topnlink>.This library is useful for the C<find2perl> tool, which when fed,    find2perl / -name .nfs\* -mtime +7 \        -exec rm -f {} \; -o -fstype nfs -pruneproduces something like:    sub wanted {        /^\.nfs.*\z/s &&        (($dev, $ino, $mode, $nlink, $uid, $gid) = lstat($_)) &&        int(-M _) > 7 &&        unlink($_)        ||        ($nlink || (($dev, $ino, $mode, $nlink, $uid, $gid) = lstat($_))) &&        $dev < 0 &&        ($File::Find::prune = 1);    }Notice the C<_> in the above C<int(-M _)>: the C<_> is a magicalfilehandle that caches the information from the precedingC<stat()>, C<lstat()>, or filetest.Here's another interesting wanted function.  It will find all symboliclinks that don't resolve:    sub wanted {         -l && !-e && print "bogus link: $File::Find::name\n";    }See also the script C<pfind> on CPAN for a nice application of thismodule.=head1 WARNINGSIf you run your program with the C<-w> switch, or if you use theC<warnings> pragma, File::Find will report warnings for several weirdsituations. You can disable these warnings by putting the statement    no warnings 'File::Find';in the appropriate scope. See L<perllexwarn> for more info about lexicalwarnings.=head1 CAVEAT=over 2=item $dont_use_nlinkYou can set the variable C<$File::Find::dont_use_nlink> to 1, if you want toforce File::Find to always stat directories. This was used for file systemsthat do not have an C<nlink> count matching the number of sub-directories.Examples are ISO-9660 (CD-ROM), AFS, HPFS (OS/2 file system), FAT (DOS filesystem) and a couple of others.You shouldn't need to set this variable, since File::Find should now detectsuch file systems on-the-fly and switch itself to using stat. This works evenfor parts of your file system, like a mounted CD-ROM.If you do set C<$File::Find::dont_use_nlink> to 1, you will notice slow-downs.=item symlinksBe aware that the option to follow symbolic links can be dangerous.Depending on the structure of the directory tree (including symboliclinks to directories) you might traverse a given (physical) directorymore than once (only if C<follow_fast> is in effect).Furthermore, deleting or changing files in a symbolically linked directorymight cause very unpleasant surprises, since you delete or change filesin an unknown directory.=back=head1 NOTES=over 4=item *Mac OS (Classic) users should note a few differences:=over 4=item *The path separator is ':', not '/', and the current directory is denotedas ':', not '.'. You should be careful about specifying relative pathnames.While a full path always begins with a volume name, a relative pathnameshould always begin with a ':'.  If specifying a volume name only, atrailing ':' is required.=item *C<$File::Find::dir> is guaranteed to end with a ':'. If C<$_>contains the name of a directory, that name may or may not end with a':'. Likewise, C<$File::Find::name>, which contains the completepathname to that directory, and C<$File::Find::fullname>, which holdsthe absolute pathname of that directory with all symbolic links resolved,may or may not end with a ':'.=item *The default C<untaint_pattern> (see above) on Mac OS is set toC<qr|^(.+)$|>. Note that the parentheses are vital.=item *The invisible system file "Icon\015" is ignored. While this file mayappear in every directory, there are some more invisible system fileson every volume, which are all located at the volume root level (i.e."MacintoshHD:"). These system files are B<not> excluded automatically.Your filter may use the following code to recognize invisible files ordirectories (requires Mac::Files): use Mac::Files; # invisible() --  returns 1 if file/directory is invisible, # 0 if it's visible or undef if an error occurred sub invisible($) {   my $file = shift;   my ($fileCat, $fileInfo);   my $invisible_flag =  1 << 14;   if ( $fileCat = FSpGetCatInfo($file) ) {     if ($fileInfo = $fileCat->ioFlFndrInfo() ) {       return (($fileInfo->fdFlags & $invisible_flag) && 1);     }   }   return undef; }Generally, invisible files are system files, unless an odd applicationdecides to use invisible files for its own purposes. To distinguishsuch files from system files, you have to look at the B<type> and B<creator>file attributes. The MacPerl built-in functions C<GetFileInfo(FILE)> andC<SetFileInfo(CREATOR, TYPE, FILES)> offer access to these attributes(see MacPerl.pm for details).Files that appear on the desktop actually reside in an (hidden) directorynamed "Desktop Folder" on the particular disk volume. Note that, althoughall desktop files appear to be on the same "virtual" desktop, each diskvolume actually maintains its own "Desktop Folder" directory.=back=back=head1 BUGS AND CAVEATSDespite the name of the C<finddepth()> function, both C<find()> andC<finddepth()> perform a depth-first search of the directoryhierarchy.=head1 HISTORYFile::Find used to produce incorrect results if called recursively.During the development of perl 5.8 this bug was fixed.The first fixed version of File::Find was 1.01.=cutour @ISA = qw(Exporter);our @EXPORT = qw(find finddepth);use strict;my $Is_VMS;my $Is_MacOS;require File::Basename;require File::Spec;# Should ideally be my() not our() but local() currently# refuses to operate on lexicals

⌨️ 快捷键说明

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