File::Find(3perl)
π File::Find(3perl) β a.k.a. the "walk the whole directory tree like it's a runway" module π
okay bestie, sit down, hydrate, because this one is a banger. it's File::Find, it lives in the Perl Programmers Reference Guide, and it is literally the tool that walks a whole directory tree for you and does stuff to every single file it finds. yes, like the Unix find(1) command. no, it does not get tired. slay.
β¨ NAME β¨
File::Find β Traverse a directory tree. that's it, that's the whole job description. π
π SYNOPSIS π
here's the vibe, three flavors:
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 }, '.');
yes ma'am, find and finddepth, two icons, both exported. π«Ά
π¦ DESCRIPTION π¦
so these are functions for searching through directory trees and doing work on each file you find β same energy as the Unix find(1) command, but make it Perl. File::Find exports two functions: find and finddepth. they work similarly but there are subtle differences, and by "subtle" I mean the order of literally everything. π
πΈ find πΈ
find(\&wanted, @directories);
find(\%options, @directories);
find() does a depth-first search over the given @directories in the order they are given. for each file or directory it finds, it calls the &wanted subroutine. (scroll down for the whole tea on how to use &wanted.) and also β for each directory it finds, it will chdir() into that directory and keep searching, invoking &wanted on every file or subdirectory in there. so thorough. so committed. π
π§ finddepth π§
finddepth(\&wanted, @directories);
finddepth(\%options, @directories);
finddepth() works just like find() except it calls &wanted for a directory after it's already called it for that directory's contents. it's a postorder traversal instead of a preorder traversal β it works from the bottom of the tree up, while find() works from the top of the tree down. bottom-up girlie behavior, honestly iconic.
and despite what the namefinddepth()is giving, bothfind()andfinddepth()perform a depth-first search of the directory hierarchy. don't let the naming gaslight you. π
β %options β
the first argument to find() is either a code reference to your &wanted function, or a hash reference describing the operations to be performed on each file. the code reference is described in "The wanted function" below (spoiler alert).
here are the possible keys for that hash, bestie, one by one, no skipping:
wantedβ the value should be a code reference. this code reference is described in "The wanted function" below. the&wantedsubroutine is mandatory. like, you cannot skip it. it's the whole point. πbydepthβ reports the name of a directory only AFTER all its entries have been reported. the entry pointfinddepth()is a shortcut for specifying{ bydepth => 1 }in the first argument offind(). cute little alias, love that for us.preprocessβ the value should be a code reference. this code reference is used to preprocess the current directory. the name of the currently processed directory is in$File::Find::dir. your preprocessing function is called afterreaddir(), but before the loop that calls thewanted()function. it's called with a list of strings (actually file/directory names) and is expected to return a list of strings. the code can be used to sort the file/directory names alphabetically, numerically, or to filter out directory entries based on their name alone. whenfolloworfollow_fastare in effect,preprocessis a no-op. πpostprocessβ the value should be a code reference. it's invoked just before leaving the currently processed directory. it's called in void context with no arguments. the name of the current directory is in$File::Find::dir. this hook is handy for summarizing a directory, like calculating its disk usage. whenfolloworfollow_fastare in effect,postprocessis a no-op. same energy as above fr.followβ causes symbolic links to be followed. now listen: since directory trees with symbolic links (followed) may contain files more than once and may even have cycles, a hash has to be built up with an entry for each file. this might be expensive both in space and time for a large directory tree. seefollow_fastandfollow_skipbelow. if eitherfolloworfollow_fastis in effect:- it is guaranteed that an
lstathas been called before the user'swanted()function is called. this enables fast file checks involving_. note that this guarantee no longer holds iffolloworfollow_fastare not set. read that again, carefully. π - there is a variable
$File::Find::fullnamewhich holds the absolute pathname of the file with all symbolic links resolved. if the link is a dangling symbolic link, thenfullnamewill be set toundef.
- it is guaranteed that an
follow_fastβ this is similar tofollowexcept that it may report some files more than once. it does detect cycles, however. since only symbolic links have to be hashed, this is much cheaper both in space and time. if processing a file more than once (by the user'swanted()function) is worse than just taking time, the optionfollowshould be used instead. trade-offs, bestie, always trade-offs.follow_skipβ three settings, three moods:follow_skip==1, which is the default, causes all files which are neither directories nor symbolic links to be ignored if they are about to be processed a second time. if a directory or a symbolic link are about to be processed a second time,File::Finddies.follow_skip==0causesFile::Findto die if any file is about to be processed a second time.follow_skip==2causesFile::Findto ignore any duplicate files and directories but to proceed normally otherwise.
dangling_symlinksβ specifies what to do with symbolic links whose target doesn't exist. if true and a code reference, will be called with the symbolic link name and the directory it lives in as arguments. otherwise, if true and warnings are on, a warning of the formsymbolic_link_name is a dangling symbolic link\nwill be issued. if false, the dangling symbolic link will be silently ignored. ghosted. π«₯no_chdirβ does notchdir()to each directory as it recurses. thewanted()function will need to be aware of this, of course. in this case,$_will be the same as$File::Find::name. stay in your lane, literally.untaintβ if find is used in taint-mode (-Tcommand line switch orif EUID != UIDorif EGID != GID), then internally directory names have to be untainted before they can bechdir'd to. therefore they are checked against a regular expressionuntaint_pattern. note that all names passed to the user'swanted()function are still tainted. if this option is used while not in taint-mode,untaintis a no-op.untaint_patternβ see above. this should be set using theqrquoting operator. the default is set toqr|^([-+@\w./]+)$|. note that the parentheses are vital. do not remove the parentheses. i am begging you. πuntaint_skipβ if set, a directory which fails theuntaint_patternis skipped, including all its sub-directories. the default is todiein such a case. yeah. dying is the default. dramatic but fair.
π The wanted function π
the wanted() function does whatever verifications you want on each file and directory. and note β despite its name, wanted() is a generic callback function, and it does not tell File::Find whether a file is "wanted" or not. in fact, its return value is ignored. it's just there to vibe and do work. its opinion does not get reported back. π
the wanted function takes no arguments but rather does its work through a collection of variables:
$File::Find::dir is the current directory name, $_ is the current filename within that directory $File::Find::name is the complete pathname to the file.
the above variables have all been localized and may be changed without affecting data outside of the wanted function. go off, be free.
for example, when examining the file /some/path/foo.ext you will have:
$File::Find::dir = /some/path/
$_ = foo.ext
$File::Find::name = /some/path/foo.ext
you are chdir()'d to $File::Find::dir when the function is called, unless no_chdir was specified. note that when changing to directories is in effect, the root directory (/) is a somewhat special case inasmuch as the concatenation of $File::Find::dir, / and $_ is not literally equal to $File::Find::name. the table below summarizes all variants β yes it's a table, yes it's going in a code block, deal with it:
$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/x
when follow or follow_fast are in effect, there is also a $File::Find::fullname. the function may set $File::Find::prune to prune the tree unless bydepth was specified. unless follow or follow_fast is specified, for compatibility reasons (find.pl, find2perl) there are in addition the following globals available: $File::Find::topdir, $File::Find::topdev, $File::Find::topino, $File::Find::topmode and $File::Find::topnlink. the whole squad, present. π
this library is useful for the find2perl tool (distributed with the App::find2perl CPAN module), which when fed:
find2perl / -name .nfs\* -mtime +7 \
-exec rm -f {} \; -o -fstype nfs -prune
produces 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 _ in the above int(-M _): the _ is a magical filehandle that caches the information from the preceding stat(), lstat(), or filetest. magical. no cap. β¨
here's another interesting wanted function. it will find all symbolic links that don't resolve:
sub wanted {
-l && !-e && print "bogus link: $File::Find::name\n";
}
note that you may mix directories and (non-directory) files in the list of directories to be searched by the wanted() function. yes, really:
find(\&wanted, "./foo", "./bar", "./baz/epsilon");
in the example above, no file in ./baz/ other than ./baz/epsilon will be evaluated by wanted(). important. don't get caught lacking on that one. π«Ά
see also the script pfind on CPAN for a nice application of this module.
π₯ WARNINGS π₯
if you run your program with the -w switch, or if you use the warnings pragma, File::Find will report warnings for several weird situations. you can disable these warnings by putting the statement
no warnings 'File::Find';
in the appropriate scope. see warnings for more info about lexical warnings.
fr fr, that's the whole warnings section. no warnings 'File::Find'; and u good. π
π BUGS AND CAVEATS π
okay bestie, real talk time β this is the part where we spill the tea on the messy bits, because File::Find is iconic but even icons have lore β¨. no cap.
π¦ $dont_use_nlink π¦
so there's this variable, $File::Find::dont_use_nlink, and you can lowkey set it to 0 if you're sure the filesystem you're scanning actually reflects the number of subdirectories in the parent directory's nlink count. like, you have to be certain certain. iykyk.
if you do set $File::Find::dont_use_nlink to 0, you might notice a speed glow-up π₯ β but it's giving risk, because it comes with the danger of not recursing into subdirectories if a filesystem doesn't populate nlink as expected. so it's a trade: faster vibes, possible skipped dirs. choose wisely π
.
$File::Find::dont_use_nlink now defaults to 1 on all platforms. periodt.
πΈ Symlinks πΈ
bestie, be aware: the option to follow symbolic links can be dangerous. not me being dramatic β it's literally in the manual.
depending on the structure of the directory tree (including symbolic links to directories), you might traverse a given (physical) directory more than once (only if follow_fast is in effect). yes, the same physical directory twice. it's giving dΓ©jΓ vu π.
and furthermore β deleting or changing files in a symbolically linked directory might cause very unpleasant surprises, since you delete or change files in an unknown directory. unknowable. chaotic. do not recommend π.
β οΈ follow symlinks at your own risk, bestie. the directory tree is not always your friend.
π HISTORY π
so back in the day, File::Find used to produce incorrect results if called recursively. messy behavior, not slay at all π.
during the development of perl 5.8 this bug was fixed. the first fixed version of File::Find was 1.01. and we've been thriving ever since π.
π SEE ALSO π
find(1)β the OG command-line iconfind2perl
that's the whole page, bestie π«Ά. this one came from perl v5.44.0, dated 2026-10-17, filed under File::Find(3perl). go forth and recurse responsibly β¨ππ§
π¦ where this page comes from
- arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms