Perl Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 5.00

DirTree.pl - Displaying the Directory Tree

This section provides a tutorial example, DirTree.pl, using a recursive method to read directories to print out a directory tree.

Both Unix and Windows systems organize file directories into a tree structure. The following program. DirTree.pl, shows you how to traverse the directory tree, and display directory entries:

#- DirTree.pl
#- Copyright (c) 1995 by Dr. Herong Yang, http://www.herongyang.com/
#
   ($dir) = @ARGV;
   $dir = "." unless $dir;
   &loopDir($dir, "");
   exit;
sub loopDir {
   local($dir, $margin) = @_;
   chdir($dir) || die "Cannot chdir to $dir\n";
   local(*DIR);
   opendir(DIR, ".");
   while ($f=readdir(DIR)) {
      next if ($f eq "." || $f eq "..");
      print "$margin$f\n";
      if (-d $f) {
         &loopDir($f,$margin."   ");
      }
   }
   closedir(DIR);
   chdir("..");
}

Be careful, don't try this program in the root directory. It will produce a very very long list of files and directories. I tried it on the working directory where I stored my Perl notes and programs, and I got the following:

>DirTree.pl ..
htm
   about.html
   active_perl.html
   book.css
   book_fo.xsl
   dot.gif
   help.html
   open.html
   opendir.html
   reference.html
   toc.html
   ...
src
   DirTree.pl
   hello.pl
   hello.prg
   opendir.pl
   ...

If you review DirTree.pl, you will see some interesting statements and techniques:

  • " $dir = "." unless $dir;" is used to assume a default directory, if nothing specified on the command line.
  • " local($dir, $margin) = @_;" is used to make $dir and $margin as local variables. This very important, since loopDir() is called recursively.
  • " local(*DIR);" is used to make DIR as local variable in any name spaces, including directory handle name space. In fact, this is the only way to make directory handle names local.
  • " if (-d $f) {" is used to test the directory entry to see if it is a directory.

Sections in This Chapter

opendir() - Open Directory to Read File Names

opendir.pl - Sample Program to Read Directories

DirTree.pl - Displaying the Directory Tree

DirGrep.pl - Searching Text in Directory Files

Dr. Herong Yang, updated in 2008
DirTree.pl - Displaying the Directory Tree