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/jane/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.

Perl

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

Detail

  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
  14. Split Line by Regex

Advanced

  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. List Modules, Search Paths
  4. Write a Module
  5. Read / Write File
  6. Traverse Dir
  7. Find / Replace
  8. Complex Numbers
  9. System Call
  10. Compress / Decompress gzip
  11. Get Env Var
  12. GET Web Content
  13. Unicode 🐪
  14. Convert File Encoding
  15. Sort Unstable