{
    "mode": "perldoc",
    "parameter": "File::Path",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/File%3A%3APath/json",
    "generated": "2026-05-30T06:05:42Z",
    "synopsis": "use File::Path qw(makepath removetree);\n@created = makepath('foo/bar/baz', '/zug/zwang');\n@created = makepath('foo/bar/baz', '/zug/zwang', {\nverbose => 1,\nmode => 0711,\n});\nmakepath('foo/bar/baz', '/zug/zwang', {\nchmod => 0777,\n});\n$removedcount = removetree('foo/bar/baz', '/zug/zwang', {\nverbose => 1,\nerror  => \\my $errlist,\nsafe => 1,\n});\n# legacy (interface promoted before v2.00)\n@created = mkpath('/foo/bar/baz');\n@created = mkpath('/foo/bar/baz', 1, 0711);\n@created = mkpath(['/foo/bar/baz', 'blurfl/quux'], 1, 0711);\n$removedcount = rmtree('foo/bar/baz', 1, 1);\n$removedcount = rmtree(['foo/bar/baz', 'blurfl/quux'], 1, 1);\n# legacy (interface promoted before v2.06)\n@created = mkpath('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });\n$removedcount = rmtree('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });",
    "sections": {
        "NAME": {
            "content": "File::Path - Create or remove directory trees\n",
            "subsections": []
        },
        "VERSION": {
            "content": "2.18 - released November 4 2020.\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use File::Path qw(makepath removetree);\n\n@created = makepath('foo/bar/baz', '/zug/zwang');\n@created = makepath('foo/bar/baz', '/zug/zwang', {\nverbose => 1,\nmode => 0711,\n});\nmakepath('foo/bar/baz', '/zug/zwang', {\nchmod => 0777,\n});\n\n$removedcount = removetree('foo/bar/baz', '/zug/zwang', {\nverbose => 1,\nerror  => \\my $errlist,\nsafe => 1,\n});\n\n# legacy (interface promoted before v2.00)\n@created = mkpath('/foo/bar/baz');\n@created = mkpath('/foo/bar/baz', 1, 0711);\n@created = mkpath(['/foo/bar/baz', 'blurfl/quux'], 1, 0711);\n$removedcount = rmtree('foo/bar/baz', 1, 1);\n$removedcount = rmtree(['foo/bar/baz', 'blurfl/quux'], 1, 1);\n\n# legacy (interface promoted before v2.06)\n@created = mkpath('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });\n$removedcount = rmtree('foo/bar/baz', '/zug/zwang', { verbose => 1, mode => 0711 });\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This module provides a convenient way to create directories of arbitrary\ndepth and to delete an entire directory subtree from the filesystem.\n\nThe following functions are provided:\n\nmakepath( $dir1, $dir2, .... )\nmakepath( $dir1, $dir2, ...., \\%opts )\nThe \"makepath\" function creates the given directories if they don't\nexist before, much like the Unix command \"mkdir -p\".\n\nThe function accepts a list of directories to be created. Its\nbehaviour may be tuned by an optional hashref appearing as the last\nparameter on the call.\n\nThe function returns the list of directories actually created during\nthe call; in scalar context the number of directories created.\n\nThe following keys are recognised in the option hash:\n\nmode => $num\nThe numeric permissions mode to apply to each created directory\n(defaults to 0777), to be modified by the current \"umask\". If\nthe directory already exists (and thus does not need to be\ncreated), the permissions will not be modified.\n\n\"mask\" is recognised as an alias for this parameter.\n\nchmod => $num\nTakes a numeric mode to apply to each created directory (not\nmodified by the current \"umask\"). If the directory already\nexists (and thus does not need to be created), the permissions\nwill not be modified.\n\nverbose => $bool\nIf present, will cause \"makepath\" to print the name of each\ndirectory as it is created. By default nothing is printed.\n\nerror => \\$err\nIf present, it should be a reference to a scalar. This scalar\nwill be made to reference an array, which will be used to store\nany errors that are encountered. See the \"ERROR HANDLING\"\nsection for more information.\n\nIf this parameter is not used, certain error conditions may\nraise a fatal error that will cause the program to halt, unless\ntrapped in an \"eval\" block.\n\nowner => $owner\nuser => $owner\nuid => $owner\nIf present, will cause any created directory to be owned by\n$owner. If the value is numeric, it will be interpreted as a\nuid; otherwise a username is assumed. An error will be issued if\nthe username cannot be mapped to a uid, the uid does not exist\nor the process lacks the privileges to change ownership.\n\nOwnership of directories that already exist will not be changed.\n\n\"user\" and \"uid\" are aliases of \"owner\".\n\ngroup => $group\nIf present, will cause any created directory to be owned by the\ngroup $group. If the value is numeric, it will be interpreted as\na gid; otherwise a group name is assumed. An error will be\nissued if the group name cannot be mapped to a gid, the gid does\nnot exist or the process lacks the privileges to change group\nownership.\n\nGroup ownership of directories that already exist will not be\nchanged.\n\nmakepath '/var/tmp/webcache', {owner=>'nobody', group=>'nogroup'};\n\nmkpath( $dir )\nmkpath( $dir, $verbose, $mode )\nmkpath( [$dir1, $dir2,...], $verbose, $mode )\nmkpath( $dir1, $dir2,..., \\%opt )\nThe \"mkpath()\" function provide the legacy interface of\n\"makepath()\" with a different interpretation of the arguments\npassed. The behaviour and return value of the function is otherwise\nidentical to \"makepath()\".\n\nremovetree( $dir1, $dir2, .... )\nremovetree( $dir1, $dir2, ...., \\%opts )\nThe \"removetree\" function deletes the given directories and any\nfiles and subdirectories they might contain, much like the Unix\ncommand \"rm -rf\" or the Windows commands \"rmdir /s\" and \"rd /s\".\n\nThe function accepts a list of directories to be removed. (In point\nof fact, it will also accept filesystem entries which are not\ndirectories, such as regular files and symlinks. But, as its name\nsuggests, its intent is to remove trees rather than individual\nfiles.)\n\n\"removetree()\"'s behaviour may be tuned by an optional hashref\nappearing as the last parameter on the call. If an empty string is\npassed to \"removetree\", an error will occur.\n\nNOTE: For security reasons, we strongly advise use of the\nhashref-as-final-argument syntax -- specifically, with a setting of\nthe \"safe\" element to a true value.\n\nremovetree( $dir1, $dir2, ....,\n{\nsafe => 1,\n...         # other key-value pairs\n},\n);\n\nThe function returns the number of files successfully deleted.\n\nThe following keys are recognised in the option hash:\n\nverbose => $bool\nIf present, will cause \"removetree\" to print the name of each\nfile as it is unlinked. By default nothing is printed.\n\nsafe => $bool\nWhen set to a true value, will cause \"removetree\" to skip the\nfiles for which the process lacks the required privileges needed\nto delete files, such as delete privileges on VMS. In other\nwords, the code will make no attempt to alter file permissions.\nThus, if the process is interrupted, no filesystem object will\nbe left in a more permissive mode.\n\nkeeproot => $bool\nWhen set to a true value, will cause all files and\nsubdirectories to be removed, except the initially specified\ndirectories. This comes in handy when cleaning out an\napplication's scratch directory.\n\nremovetree( '/tmp', {keeproot => 1} );\n\nresult => \\$res\nIf present, it should be a reference to a scalar. This scalar\nwill be made to reference an array, which will be used to store\nall files and directories unlinked during the call. If nothing\nis unlinked, the array will be empty.\n\nremovetree( '/tmp', {result => \\my $list} );\nprint \"unlinked $\\n\" for @$list;\n\nThis is a useful alternative to the \"verbose\" key.\n\nerror => \\$err\nIf present, it should be a reference to a scalar. This scalar\nwill be made to reference an array, which will be used to store\nany errors that are encountered. See the \"ERROR HANDLING\"\nsection for more information.\n\nRemoving things is a much more dangerous proposition than\ncreating things. As such, there are certain conditions that\n\"removetree\" may encounter that are so dangerous that the only\nsane action left is to kill the program.\n\nUse \"error\" to trap all that is reasonable (problems with\npermissions and the like), and let it die if things get out of\nhand. This is the safest course of action.\n\nrmtree( $dir )\nrmtree( $dir, $verbose, $safe )\nrmtree( [$dir1, $dir2,...], $verbose, $safe )\nrmtree( $dir1, $dir2,..., \\%opt )\nThe \"rmtree()\" function provide the legacy interface of\n\"removetree()\" with a different interpretation of the arguments\npassed. The behaviour and return value of the function is otherwise\nidentical to \"removetree()\".\n\nNOTE: For security reasons, we strongly advise use of the\nhashref-as-final-argument syntax, specifically with a setting of the\n\"safe\" element to a true value.\n\nrmtree( $dir1, $dir2, ....,\n{\nsafe => 1,\n...         # other key-value pairs\n},\n);\n\nERROR HANDLING\nNOTE:\nThe following error handling mechanism is consistent throughout all\ncode paths EXCEPT in cases where the ROOT node is nonexistent. In\nversion 2.11 the maintainers attempted to rectify this inconsistency\nbut too many downstream modules encountered problems. In such case,\nif you require root node evaluation or error checking prior to\ncalling \"makepath\" or \"removetree\", you should take additional\nprecautions.\n\nIf \"makepath\" or \"removetree\" encounters an error, a diagnostic\nmessage will be printed to \"STDERR\" via \"carp\" (for non-fatal errors) or\nvia \"croak\" (for fatal errors).\n\nIf this behaviour is not desirable, the \"error\" attribute may be used to\nhold a reference to a variable, which will be used to store the\ndiagnostics. The variable is made a reference to an array of hash\nreferences. Each hash contain a single key/value pair where the key is\nthe name of the file, and the value is the error message (including the\ncontents of $! when appropriate). If a general error is encountered the\ndiagnostic key will be empty.\n\nAn example usage looks like:\n\nremovetree( 'foo/bar', 'bar/rat', {error => \\my $err} );\nif ($err && @$err) {\nfor my $diag (@$err) {\nmy ($file, $message) = %$diag;\nif ($file eq '') {\nprint \"general error: $message\\n\";\n}\nelse {\nprint \"problem unlinking $file: $message\\n\";\n}\n}\n}\nelse {\nprint \"No error encountered\\n\";\n}\n\nNote that if no errors are encountered, $err will reference an empty\narray. This means that $err will always end up TRUE; so you need to test\n@$err to determine if errors occurred.\n\nNOTES\n\"File::Path\" blindly exports \"mkpath\" and \"rmtree\" into the current\nnamespace. These days, this is considered bad style, but to change it\nnow would break too much code. Nonetheless, you are invited to specify\nwhat it is you are expecting to use:\n\nuse File::Path 'rmtree';\n\nThe routines \"makepath\" and \"removetree\" are not exported by default.\nYou must specify which ones you want to use.\n\nuse File::Path 'removetree';\n\nNote that a side-effect of the above is that \"mkpath\" and \"rmtree\" are\nno longer exported at all. This is due to the way the \"Exporter\" module\nworks. If you are migrating a codebase to use the new interface, you\nwill have to list everything explicitly. But that's just good practice\nanyway.\n\nuse File::Path qw(removetree rmtree);\n\nAPI CHANGES\nThe API was changed in the 2.0 branch. For a time, \"mkpath\" and \"rmtree\"\ntried, unsuccessfully, to deal with the two different calling\nmechanisms. This approach was considered a failure.\n\nThe new semantics are now only available with \"makepath\" and\n\"removetree\". The old semantics are only available through \"mkpath\" and\n\"rmtree\". Users are strongly encouraged to upgrade to at least 2.08 in\norder to avoid surprises.\n\nSECURITY CONSIDERATIONS\nThere were race conditions in the 1.x implementations of File::Path's\n\"rmtree\" function (although sometimes patched depending on the OS\ndistribution or platform). The 2.0 version contains code to avoid the\nproblem mentioned in CVE-2002-0435.\n\nSee the following pages for more information:\n\nhttp://bugs.debian.org/cgi-bin/bugreport.cgi?bug=286905\nhttp://www.nntp.perl.org/group/perl.perl5.porters/2005/01/msg97623.html\nhttp://www.debian.org/security/2005/dsa-696\n\nAdditionally, unless the \"safe\" parameter is set (or the third parameter\nin the traditional interface is TRUE), should a \"removetree\" be\ninterrupted, files that were originally in read-only mode may now have\ntheir permissions set to a read-write (or \"delete OK\") mode.\n\nThe following CVE reports were previously filed against File-Path and\nare believed to have been addressed:\n\n*   <http://cve.circl.lu/cve/CVE-2004-0452>\n\n*   <http://cve.circl.lu/cve/CVE-2005-0448>\n\nIn February 2017 the cPanel Security Team reported an additional\nvulnerability in File-Path. The \"chmod()\" logic to make directories\ntraversable can be abused to set the mode on an attacker-chosen file to\nan attacker-chosen value. This is due to the\ntime-of-check-to-time-of-use (TOCTTOU) race condition\n(<https://en.wikipedia.org/wiki/Timeofchecktotimeofuse>) between\nthe \"stat()\" that decides the inode is a directory and the \"chmod()\"\nthat tries to make it user-rwx. CPAN versions 2.13 and later incorporate\na patch provided by John Lightsey to address this problem. This\nvulnerability has been reported as CVE-2017-6512.\n",
            "subsections": []
        },
        "DIAGNOSTICS": {
            "content": "FATAL errors will cause the program to halt (\"croak\"), since the problem\nis so severe that it would be dangerous to continue. (This can always be\ntrapped with \"eval\", but it's not a good idea. Under the circumstances,\ndying is the best thing to do).\n\nSEVERE errors may be trapped using the modern interface. If the they are\nnot trapped, or if the old interface is used, such an error will cause\nthe program will halt.\n\nAll other errors may be trapped using the modern interface, otherwise\nthey will be \"carp\"ed about. Program execution will not be halted.\n\nmkdir [path]: [errmsg] (SEVERE)\n\"makepath\" was unable to create the path. Probably some sort of\npermissions error at the point of departure or insufficient\nresources (such as free inodes on Unix).\n\nNo root path(s) specified\n\"makepath\" was not given any paths to create. This message is only\nemitted if the routine is called with the traditional interface. The\nmodern interface will remain silent if given nothing to do.\n\nNo such file or directory\nOn Windows, if \"makepath\" gives you this warning, it may mean that\nyou have exceeded your filesystem's maximum path length.\n\ncannot fetch initial working directory: [errmsg]\n\"removetree\" attempted to determine the initial directory by\ncalling \"Cwd::getcwd\", but the call failed for some reason. No\nattempt will be made to delete anything.\n\ncannot stat initial working directory: [errmsg]\n\"removetree\" attempted to stat the initial directory (after having\nsuccessfully obtained its name via \"getcwd\"), however, the call\nfailed for some reason. No attempt will be made to delete anything.\n\ncannot chdir to [dir]: [errmsg]\n\"removetree\" attempted to set the working directory in order to\nbegin deleting the objects therein, but was unsuccessful. This is\nusually a permissions issue. The routine will continue to delete\nother things, but this directory will be left intact.\n\ndirectory [dir] changed before chdir, expected dev=[n] ino=[n], actual\ndev=[n] ino=[n], aborting. (FATAL)\n\"removetree\" recorded the device and inode of a directory, and then\nmoved into it. It then performed a \"stat\" on the current directory\nand detected that the device and inode were no longer the same. As\nthis is at the heart of the race condition problem, the program will\ndie at this point.\n\ncannot make directory [dir] read+writeable: [errmsg]\n\"removetree\" attempted to change the permissions on the current\ndirectory to ensure that subsequent unlinkings would not run into\nproblems, but was unable to do so. The permissions remain as they\nwere, and the program will carry on, doing the best it can.\n\ncannot read [dir]: [errmsg]\n\"removetree\" tried to read the contents of the directory in order\nto acquire the names of the directory entries to be unlinked, but\nwas unsuccessful. This is usually a permissions issue. The program\nwill continue, but the files in this directory will remain after the\ncall.\n\ncannot reset chmod [dir]: [errmsg]\n\"removetree\", after having deleted everything in a directory,\nattempted to restore its permissions to the original state but\nfailed. The directory may wind up being left behind.\n\ncannot remove [dir] when cwd is [dir]\nThe current working directory of the program is /some/path/to/here\nand you are attempting to remove an ancestor, such as /some/path.\nThe directory tree is left untouched.\n\nThe solution is to \"chdir\" out of the child directory to a place\noutside the directory tree to be removed.\n\ncannot chdir to [parent-dir] from [child-dir]: [errmsg], aborting.\n(FATAL)\n\"removetree\", after having deleted everything and restored the\npermissions of a directory, was unable to chdir back to the parent.\nThe program halts to avoid a race condition from occurring.\n\ncannot stat prior working directory [dir]: [errmsg], aborting. (FATAL)\n\"removetree\" was unable to stat the parent directory after having\nreturned from the child. Since there is no way of knowing if we\nreturned to where we think we should be (by comparing device and\ninode) the only way out is to \"croak\".\n\nprevious directory [parent-dir] changed before entering [child-dir],\nexpected dev=[n] ino=[n], actual dev=[n] ino=[n], aborting. (FATAL)\nWhen \"removetree\" returned from deleting files in a child\ndirectory, a check revealed that the parent directory it returned to\nwasn't the one it started out from. This is considered a sign of\nmalicious activity.\n\ncannot make directory [dir] writeable: [errmsg]\nJust before removing a directory (after having successfully removed\neverything it contained), \"removetree\" attempted to set the\npermissions on the directory to ensure it could be removed and\nfailed. Program execution continues, but the directory may possibly\nnot be deleted.\n\ncannot remove directory [dir]: [errmsg]\n\"removetree\" attempted to remove a directory, but failed. This may\nbe because some objects that were unable to be removed remain in the\ndirectory, or it could be a permissions issue. The directory will be\nleft behind.\n\ncannot restore permissions of [dir] to [0nnn]: [errmsg]\nAfter having failed to remove a directory, \"removetree\" was unable\nto restore its permissions from a permissive state back to a\npossibly more restrictive setting. (Permissions given in octal).\n\ncannot make file [file] writeable: [errmsg]\n\"removetree\" attempted to force the permissions of a file to ensure\nit could be deleted, but failed to do so. It will, however, still\nattempt to unlink the file.\n\ncannot unlink file [file]: [errmsg]\n\"removetree\" failed to remove a file. Probably a permissions issue.\n\ncannot restore permissions of [file] to [0nnn]: [errmsg]\nAfter having failed to remove a file, \"removetree\" was also unable\nto restore the permissions on the file to a possibly less permissive\nsetting. (Permissions given in octal).\n\nunable to map [owner] to a uid, ownership not changed\");\n\"makepath\" was instructed to give the ownership of created\ndirectories to the symbolic name [owner], but \"getpwnam\" did not\nreturn the corresponding numeric uid. The directory will be created,\nbut ownership will not be changed.\n\nunable to map [group] to a gid, group ownership not changed\n\"makepath\" was instructed to give the group ownership of created\ndirectories to the symbolic name [group], but \"getgrnam\" did not\nreturn the corresponding numeric gid. The directory will be created,\nbut group ownership will not be changed.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "*   File::Remove\n\nAllows files and directories to be moved to the Trashcan/Recycle Bin\n(where they may later be restored if necessary) if the operating\nsystem supports such functionality. This feature may one day be made\navailable directly in \"File::Path\".\n\n*   File::Find::Rule\n\nWhen removing directory trees, if you want to examine each file to\ndecide whether to delete it (and possibly leaving large swathes\nalone), File::Find::Rule offers a convenient and flexible approach\nto examining directory trees.\n",
            "subsections": []
        },
        "BUGS AND LIMITATIONS": {
            "content": "The following describes File::Path limitations and how to report bugs.\n\nMULTITHREADED APPLICATIONS\nFile::Path \"rmtree\" and \"removetree\" will not work with multithreaded\napplications due to its use of \"chdir\". At this time, no warning or\nerror is generated in this situation. You will certainly encounter\nunexpected results.\n\nThe implementation that surfaces this limitation will not be changed.\nSee the File::Path::Tiny module for functionality similar to File::Path\nbut which does not \"chdir\".\n\nNFS Mount Points\nFile::Path is not responsible for triggering the automounts, mirror\nmounts, and the contents of network mounted filesystems. If your NFS\nimplementation requires an action to be performed on the filesystem in\norder for File::Path to perform operations, it is strongly suggested you\nassure filesystem availability by reading the root of the mounted\nfilesystem.\n\nREPORTING BUGS\nPlease report all bugs on the RT queue, either via the web interface:\n\n<http://rt.cpan.org/NoAuth/Bugs.html?Dist=File-Path>\n\nor by email:\n\nbug-File-Path@rt.cpan.org\n\nIn either case, please attach patches to the bug report rather than\nincluding them inline in the web post or the body of the email.\n\nYou can also send pull requests to the Github repository:\n\n<https://github.com/rpcme/File-Path>\n",
            "subsections": []
        },
        "ACKNOWLEDGEMENTS": {
            "content": "Paul Szabo identified the race condition originally, and Brendan O'Dea\nwrote an implementation for Debian that addressed the problem. That code\nwas used as a basis for the current code. Their efforts are greatly\nappreciated.\n\nGisle Aas made a number of improvements to the documentation for 2.07\nand his advice and assistance is also greatly appreciated.\n",
            "subsections": []
        },
        "AUTHORS": {
            "content": "Prior authors and maintainers: Tim Bunce, Charles Bailey, and David\nLandgren <david@landgren.net>.\n\nCurrent maintainers are Richard Elberger <riche@cpan.org> and James\n(Jim) Keenan <jkeenan@cpan.org>.\n",
            "subsections": []
        },
        "CONTRIBUTORS": {
            "content": "Contributors to File::Path, in alphabetical order by first name.\n\n<bulkdd@cpan.org>\nCharlie Gonzalez <itcharlie@cpan.org>\nCraig A. Berry <craigberry@mac.com>\nJames E Keenan <jkeenan@cpan.org>\nJohn Lightsey <john@perlsec.org>\nNigel Horne <njh@bandsman.co.uk>\nRichard Elberger <riche@cpan.org>\nRyan Yee <ryee@cpan.org>\nSkye Shaw <shaw@cpan.org>\nTom Lutz <tommylutz@gmail.com>\nWill Sheppard <willsheppard@github>\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "This module is copyright (C) Charles Bailey, Tim Bunce, David Landgren,\nJames Keenan and Richard Elberger 1995-2020. All rights reserved.\n",
            "subsections": []
        },
        "LICENSE": {
            "content": "This library is free software; you can redistribute it and/or modify it\nunder the same terms as Perl itself.\n",
            "subsections": []
        }
    },
    "summary": "File::Path - Create or remove directory trees",
    "flags": [],
    "examples": [],
    "see_also": []
}