Perl Tutorials - Herong's Tutorial Examples - v6.01, by Dr. Herong Yang
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) HerongYang.com. All Rights Reserved. # ($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:
herong\src> 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:
Table of Contents
Data Types: Values and Variables
Expressions, Operations and Simple Statements
Name Spaces and Perl Module Files
Hard References - Addresses of Memory Objects
Objects (or References) and Classes (or Packages)
Typeglob and Importing Identifiers from Other Packages
String Built-in Functions and Performance
File Handles and Data Input/Output
►Open Directories and Read File Names
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
File System Functions and Operations
Socket Communication Over the Internet
XML::Simple Module - XML Parser and Generator
SOAP::Lite - SOAP Server-Client Communication Module
Perl Programs as IIS Server CGI Scripts
CGI (Common Gateway Interface)
XML-RPC - Remote Procedure Call with XML and HTTP
RPC::XML - Perl Implementation of XML-RPC
Integrating Perl with Apache Web Server
CGI.pm Module for Building Web Pages
LWP::UserAgent and Web Site Testing
Converting Perl Script to Executable Binary