scripts

Perl directory traversal

The following chunk of code

sub traverse {
    my ($dir, $callback) = @_;
    my $present;

    opendir $present, $dir or return();

    for (grep { ! /^(\.|\.\.)$/ } readdir $present) {
        my $path = "$dir/$_";

        &$callback($path);
        traverse($path, $callback) if -d $path;
    }

    closedir $present;
    return();
}

is an easy implementation (without error-checking) of a generic directory-traversing function in Perl. It should be called

traverse(dir, sub)

where dir is a directory name and sub is a reference to a subroutine. A trivial example:

sub textP {
  my $file = shift;
  if (-T $file) {
    print "[$file] is a text file\n";
  } else {
    print "[$file] is NOT a text file\n";
  }
  return;
}

traverse(".", \&textP);

All the above is well-known and common functional-programming practice, but quite useful.

speak up

Add your comment below, or trackback from your own site.

Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*Required Fields