return to first page linux journal archive
keywordscontents

Listing 2. p2.pl Code

#!/usr/bin/perl -dw
require 5.001;
# Code to demonstrate more advanced debugging
# techniques.
# This program will start in the current directory
# and recursively locate all files in the
# directory and all subdirectories.

@files = searchdir("."); # here we go
foreach (@files) {
 print "$_\n";
}
# To do this, we'll call a subroutine that will
# open a directory and generate two arrays based.
# One will be an array of all files in the
# directory, and the other will be of all the
# subdirectories. Then, for each value in the
# subdirectory array, we'll recursively call the
# subroutine. Each time the subroutine finishes,
# it will return the # array of files.

sub searchdir { # takes a directory as an argument
 my($dir) = @_;
 my(@files, @subdirs);

 opendir(DIR,$dir) or die "Can't open \"
	$dir\" for reading: $!\n";

 while(defined($_ = readdir(DIR))) {
 /^\./ and next; # if file begins with '.', skip

 ### SUBTLE HINT ###

 if( -f $_) { # if it's a file...
  push @files, $_; # save it
 } elsif( -d $_ ) { # else if it's a directory...
  push @subdirs, $_; # save it
 }
# no else, because we will ignore things that
# aren't files or dirs
 }
 closedir DIR or warn "Huh?? Can't close \"
 $dir\": $!\n";
 foreach $_ (@subdirs) { # for each subdirectory
			 # found earlier...
 push @files, searchdir($_); # put all files found
			     # within $_ onto list
 }
 @files; # return all the file we found
} # END of searchdir