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