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 name finddepth() is giving, both find() and finddepth() 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 &wanted subroutine 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 point finddepth() is a shortcut for specifying { bydepth => 1 } in the first argument of find(). 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 after readdir(), but before the loop that calls the wanted() 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. when follow or follow_fast are in effect, preprocess is 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. when follow or follow_fast are in effect, postprocess is 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. see follow_fast and follow_skip below. if either follow or follow_fast is in effect:
    • it is guaranteed that an lstat has been called before the user's wanted() function is called. this enables fast file checks involving _. note that this guarantee no longer holds if follow or follow_fast are not set. read that again, carefully. πŸ“
    • there is a variable $File::Find::fullname which holds the absolute pathname of the file with all symbolic links resolved. if the link is a dangling symbolic link, then fullname will be set to undef.
  • follow_fast β€” this is similar to follow except 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's wanted() function) is worse than just taking time, the option follow should 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::Find dies.
    • follow_skip==0 causes File::Find to die if any file is about to be processed a second time.
    • follow_skip==2 causes File::Find to 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 form symbolic_link_name is a dangling symbolic link\n will be issued. if false, the dangling symbolic link will be silently ignored. ghosted. πŸ«₯
  • no_chdir β€” does not chdir() to each directory as it recurses. the wanted() 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 (-T command line switch or if EUID != UID or if EGID != GID), then internally directory names have to be untainted before they can be chdir'd to. therefore they are checked against a regular expression untaint_pattern. note that all names passed to the user's wanted() function are still tainted. if this option is used while not in taint-mode, untaint is a no-op.
  • untaint_pattern β€” see above. this should be set using the qr quoting operator. the default is set to qr|^([-+@\w./]+)$|. note that the parentheses are vital. do not remove the parentheses. i am begging you. 😭
  • untaint_skip β€” if set, a directory which fails the untaint_pattern is skipped, including all its sub-directories. the default is to die in 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.


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.


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 icon
  • find2perl

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