Perl: Traverse Directory

By Xah Lee. Date: . Last updated: .

In Perl, to traverse a dir, use the “find” function in use File::Find;. Example:

# -*- coding: utf-8 -*-
# perl

# traverse a directory

use File::Find qw(find);

$mydir = '/home/joe/web/';

sub wanted {

  # if file name ends in .html and is a text file
  if ($_ =~/\.html$/ && -T $File::Find::name) {
    print $File::Find::name, "\n";

find(\&wanted, $mydir);

The line use File::Find qw(find); imports the “find” function.

The “find” function is a directory walker. It will visit every file and subdir in a given directory.

The “find” function has 2 parameters. The first is a reference to a function that will be called each time when “find” visits a file. The second is the path you want to traverse.

When “find” calls your function, the following var are defined:

Note: The name “wanted” is just a convention used by the “File::Find” package. When your function “wanted” is called, nothing is passed to it as argument. This means, you cannot write your “wanted” function as a functional programing style that takes a file path as its parameter. Instead, you must call the variable $File::Find::name or $_ inside the body of “wanted” to know the current file name.

Note: also, “wanted” cannot be written as a recursive function that calls itself to decent to subdirs.

perldoc File::Find

If you have a question, put $5 at patreon and message me.


  1. Perl Overview
  2. Version String
  3. Help System


  1. Quoting String
  2. Format String
  3. String Operations
  4. True, False
  5. if then else
  6. Loop
  7. List / Array
  8. Loop Thru List
  9. Map f to List
  10. List Comprehension
  11. Hash Table
  12. Function Optional Param
  13. regex

Text Processing

  1. Unicode 🐪
  2. Convert File Encoding
  3. Read Write File
  4. Traverse Dir
  5. Find Replace
  6. Validate Local Links
  7. Split Line by Regex


  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. Sort Unstable
  4. Sort Misc
  5. List Modules, Search Paths
  6. Write a Module
  7. Complex Numbers
  8. System Call
  9. gzip
  10. Get Env Var
  11. GET Web Content
  12. Email