📄 path.pm
字号:
If present, will cause C<mkpath> to print the name of each directoryas it is created. By default nothing is printed.=item errorIf present, will be interpreted as a reference to a list, and willbe used to store any errors that are encountered. See the ERRORHANDLING section for more information.If this parameter is not used, certain error conditions may raisea fatal error that will cause the program will halt, unless trappedin an C<eval> block.=back=head3 C<rmtree>=over 4=item verboseIf present, will cause C<rmtree> to print the name of each file asit is unlinked. By default nothing is printed.=item safeWhen set to a true value, will cause C<rmtree> to skip the filesfor which the process lacks the required privileges needed to deletefiles, such as delete privileges on VMS. In other words, the codewill make no attempt to alter file permissions. Thus, if the processis interrupted, no filesystem object will be left in a morepermissive mode.=item keep_rootWhen set to a true value, will cause all files and subdirectoriesto be removed, except the initially specified directories. This comesin handy when cleaning out an application's scratch directory. rmtree( '/tmp', {keep_root => 1} );=item resultIf present, will be interpreted as a reference to a list, and willbe used to store the list of all files and directories unlinkedduring the call. If nothing is unlinked, a reference to an emptylist is returned (rather than C<undef>). rmtree( '/tmp', {result => \my $list} ); print "unlinked $_\n" for @$list;This is a useful alternative to the C<verbose> key.=item errorIf present, will be interpreted as a reference to a list,and will be used to store any errors that are encountered.See the ERROR HANDLING section for more information.Removing things is a much more dangerous proposition thancreating things. As such, there are certain conditions thatC<rmtree> may encounter that are so dangerous that the onlysane action left is to kill the program.Use C<error> to trap all that is reasonable (problems withpermissions and the like), and let it die if things get outof hand. This is the safest course of action.=back=head2 TRADITIONAL INTERFACEThe old interfaces of C<mkpath> and C<rmtree> take a reference toa list of directories (to create or remove), followed by a seriesof positional, numeric, modal parameters that control their behaviour.This design made it difficult to add additional functionality, aswell as posed the problem of what to do when the calling code onlyneeds to set the last parameter. Even though the code doesn't carehow the initial positional parameters are set, the programmer isforced to learn what the defaults are, and specify them.Worse, if it turns out in the future that it would make more senseto change the default behaviour of the first parameter (for example,to avoid a security vulnerability), all existing code will remainhard-wired to the wrong defaults.Finally, a series of numeric parameters are much less self-documentingin terms of communicating to the reader what the code is doing. Namedparameters do not have this problem.In the traditional API, C<mkpath> takes three arguments:=over 4=item *The name of the path to create, or a reference to a list of pathsto create,=item *a boolean value, which if TRUE will cause C<mkpath> to print thename of each directory as it is created (defaults to FALSE), and=item *the numeric mode to use when creating the directories (defaults to0777), to be modified by the current umask.=backIt returns a list of all directories (including intermediates, determinedusing the Unix '/' separator) created. In scalar context it returnsthe number of directories created.If a system error prevents a directory from being created, then theC<mkpath> function throws a fatal error with C<Carp::croak>. This errorcan be trapped with an C<eval> block: eval { mkpath($dir) }; if ($@) { print "Couldn't create $dir: $@"; }In the traditional API, C<rmtree> takes three arguments:=over 4=item *the root of the subtree to delete, or a reference to a list ofroots. All of the files and directories below each root, as wellas the roots themselves, will be deleted. If you want to keepthe roots themselves, you must use the modern API.=item *a boolean value, which if TRUE will cause C<rmtree> to print amessage each time it examines a file, giving the name of the file,and indicating whether it's using C<rmdir> or C<unlink> to removeit, or that it's skipping it. (defaults to FALSE)=item *a boolean value, which if TRUE will cause C<rmtree> to skip anyfiles to which you do not have delete access (if running under VMS)or write access (if running under another OS). This will changein the future when a criterion for 'delete permission' under OSsother than VMS is settled. (defaults to FALSE)=backIt returns the number of files, directories and symlinks successfullydeleted. Symlinks are simply deleted and not followed.Note also that the occurrence of errors in C<rmtree> using thetraditional interface can be determined I<only> by trapping diagnosticmessages using C<$SIG{__WARN__}>; it is not apparent from the returnvalue. (The modern interface may use the C<error> parameter torecord any problems encountered).=head2 ERROR HANDLINGIf C<mkpath> or C<rmtree> encounter an error, a diagnostic messagewill be printed to C<STDERR> via C<carp> (for non-fatal errors),or via C<croak> (for fatal errors).If this behaviour is not desirable, the C<error> attribute may beused to hold a reference to a variable, which will be used to storethe diagnostics. The result is a reference to a list of hashreferences. For each hash reference, the key is the name of thefile, and the value is the error message (usually the contents ofC<$!>). An example usage looks like: rmpath( 'foo/bar', 'bar/rat', {error => \my $err} ); for my $diag (@$err) { my ($file, $message) = each %$diag; print "problem unlinking $file: $message\n"; }If no errors are encountered, C<$err> will point to an empty list(thus there is no need to test for C<undef>). If a general erroris encountered (for instance, C<rmtree> attempts to remove a directorytree that does not exist), the diagnostic key will be empty, onlythe value will be set: rmpath( '/no/such/path', {error => \my $err} ); for my $diag (@$err) { my ($file, $message) = each %$diag; if ($file eq '') { print "general error: $message\n"; } }=head2 NOTESC<File::Path> blindly exports C<mkpath> and C<rmtree> into thecurrent namespace. These days, this is considered bad style, butto change it now would break too much code. Nonetheless, you areinvited to specify what it is you are expecting to use: use File::Path 'rmtree';=head3 HEURISTICSThe functions detect (as far as possible) which way they are beingcalled and will act appropriately. It is important to remember thatthe heuristic for detecting the old style is either the presenceof an array reference, or two or three parameters total and secondand third parameters are numeric. Hence... mkpath 486, 487, 488;... will not assume the modern style and create three directories, ratherit will create one directory verbosely, setting the permission to0750 (488 being the decimal equivalent of octal 750). Here, oldstyle trumps new. It must, for backwards compatibility reasons.If you want to ensure there is absolutely no ambiguity about whichway the function will behave, make sure the first parameter is areference to a one-element list, to force the old style interpretation: mkpath [486], 487, 488;and get only one directory created. Or add a reference to an emptyparameter hash, to force the new style: mkpath 486, 487, 488, {};... and hence create the three directories. If the empty hashreference seems a little strange to your eyes, or you suspect asubsequent programmer might I<helpfully> optimise it away, youcan add a parameter set to a default value: mkpath 486, 487, 488, {verbose => 0};=head3 SECURITY CONSIDERATIONSThere were race conditions 1.x implementations of File::Path'sC<rmtree> function (although sometimes patched depending on the OSdistribution or platform). The 2.0 version contains code to avoid theproblem mentioned in CVE-2002-0435.See the following pages for more information: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=286905 http://www.nntp.perl.org/group/perl.perl5.porters/2005/01/msg97623.html http://www.debian.org/security/2005/dsa-696Additionally, unless the C<safe> parameter is set (or thethird parameter in the traditional interface is TRUE), should aC<rmtree> be interrupted, files that were originally in read-onlymode may now have their permissions set to a read-write (or "deleteOK") mode.=head1 DIAGNOSTICSFATAL errors will cause the program to halt (C<croak>), since theproblem is so severe that it would be dangerous to continue. (Thiscan always be trapped with C<eval>, but it's not a good idea. Underthe circumstances, dying is the best thing to do).SEVERE errors may be trapped using the modern interface. If thethey are not trapped, or the old interface is used, such an errorwill cause the program will halt.All other errors may be trapped using the modern interface, otherwisethey will be C<carp>ed about. Program execution will not be halted.=over 4=item mkdir [path]: [errmsg] (SEVERE)C<mkpath> was unable to create the path. Probably some sort ofpermissions error at the point of departure, or insufficient resources(such as free inodes on Unix).=item No root path(s) specifiedC<mkpath> was not given any paths to create. This message is onlyemitted if the routine is called with the traditional interface.The modern interface will remain silent if given nothing to do.=item No such file or directoryOn Windows, if C<mkpath> gives you this warning, it may mean thatyou have exceeded your filesystem's maximum path length.=item cannot fetch initial working directory: [errmsg]C<rmtree> attempted to determine the initial directory by callingC<Cwd::getcwd>, but the call failed for some reason. No attemptwill be made to delete anything.=item cannot stat initial working directory: [errmsg]C<rmtree> attempted to stat the initial directory (after havingsuccessfully obtained its name via C<getcwd>), however, the callfailed for some reason. No attempt will be made to delete anything.=item cannot chdir to [dir]: [errmsg]C<rmtree> attempted to set the working directory in order tobegin deleting the objects therein, but was unsuccessful. This isusually a permissions issue. The routine will continue to deleteother things, but this directory will be left intact.=item directory [dir] changed before chdir, expected dev=[n] inode=[n], actual dev=[n] ino=[n], aborting. (FATAL)C<rmtree> recorded the device and inode of a directory, and thenmoved into it. It then performed a C<stat> on the current directoryand detected that the device and inode were no longer the same. Asthis is at the heart of the race condition problem, the programwill die at this point.=item cannot make directory [dir] read+writeable: [errmsg]C<rmtree> attempted to change the permissions on the current directoryto ensure that subsequent unlinkings would not run into problems,but was unable to do so. The permissions remain as they were, andthe program will carry on, doing the best it can.=item cannot read [dir]: [errmsg]C<rmtree> tried to read the contents of the directory in orderto acquire the names of the directory entries to be unlinked, butwas unsuccessful. This is usually a permissions issue. Theprogram will continue, but the files in this directory will remainafter the call.=item cannot reset chmod [dir]: [errmsg]C<rmtree>, after having deleted everything in a directory, attemptedto restore its permissions to the original state but failed. Thedirectory may wind up being left behind.=item cannot chdir to [parent-dir] from [child-dir]: [errmsg], aborting. (FATAL)C<rmtree>, after having deleted everything and restored the permissionsof a directory, was unable to chdir back to the parent. This is usuallya sign that something evil this way comes.=item cannot stat prior working directory [dir]: [errmsg], aborting. (FATAL)C<rmtree> was unable to stat the parent directory after have returnedfrom the child. Since there is no way of knowing if we returned towhere we think we should be (by comparing device and inode) the onlyway out is to C<croak>.=item previous directory [parent-dir] changed before entering [child-dir], expected dev=[n] inode=[n], actual dev=[n] ino=[n], aborting. (FATAL)When C<rmtree> returned from deleting files in a child directory, acheck revealed that the parent directory it returned to wasn't the oneit started out from. This is considered a sign of malicious activity.=item cannot make directory [dir] writeable: [errmsg]Just before removing a directory (after having successfully removedeverything it contained), C<rmtree> attempted to set the permissionson the directory to ensure it could be removed and failed. Programexecution continues, but the directory may possibly not be deleted.=item cannot remove directory [dir]: [errmsg]C<rmtree> attempted to remove a directory, but failed. This may becausesome objects that were unable to be removed remain in the directory, ora permissions issue. The directory will be left behind.=item cannot restore permissions of [dir] to [0nnn]: [errmsg]After having failed to remove a directory, C<rmtree> was unable torestore its permissions from a permissive state back to a possiblymore restrictive setting. (Permissions given in octal).=item cannot make file [file] writeable: [errmsg]C<rmtree> attempted to force the permissions of a file to ensure itcould be deleted, but failed to do so. It will, however, still attemptto unlink the file.=item cannot unlink file [file]: [errmsg]C<rmtree> failed to remove a file. Probably a permissions issue.=item cannot restore permissions of [file] to [0nnn]: [errmsg]After having failed to remove a file, C<rmtree> was also unableto restore the permissions on the file to a possibly less permissivesetting. (Permissions given in octal).=back=head1 SEE ALSO=over 4=item *L<File::Remove>Allows files and directories to be moved to the Trashcan/RecycleBin (where they may later be restored if necessary) if the operatingsystem supports such functionality. This feature may one day bemade available directly in C<File::Path>.=item *L<File::Find::Rule>When removing directory trees, if you want to examine each file todecide whether to delete it (and possibly leaving large swathesalone), F<File::Find::Rule> offers a convenient and flexible approachto examining directory trees.=back=head1 BUGSPlease report all bugs on the RT queue:L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=File-Path>=head1 ACKNOWLEDGEMENTSPaul Szabo identified the race condition originally, and BrendanO'Dea wrote an implementation for Debian that addressed the problem.That code was used as a basis for the current code. Their effortsare greatly appreciated.=head1 AUTHORSTim Bunce <F<Tim.Bunce@ig.co.uk>> and Charles Bailey<F<bailey@newman.upenn.edu>>. Currently maintained by David Landgren<F<david@landgren.net>>.=head1 COPYRIGHTThis module is copyright (C) Charles Bailey, Tim Bunce andDavid Landgren 1995-2007. All rights reserved.=head1 LICENSEThis library is free software; you can redistribute it and/or modifyit under the same terms as Perl itself.=cut
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -