PDA

View Full Version : Recursive Directory


gsoft
12-07-2004, 01:18 AM
Ok ive been reading Learning Perl damn good book, not only an interesting read ive learnt something :D

Anyway from the book they never had a recursive directory so I decided why not try and make one. It may not be efficient im sure theres a Perl Module out there for this to make a it a lot faster.


#!/usr/bin/perl

sub read_directory {

my $directory = $_[0];
print "$directory\n\n";

opendir DIR, $directory or die "Cannot open Directory $!";
my @files = readdir DIR;

for (@files) {
next if $_ eq "." or $_ eq "..";
&read_directory("$directory/$_") if -d "$directory/$_";
print "$directory/$_\n" if !-d "$directory/$_";
}
closedir DIR;

}

my $directory = "/var/www/web";
&read_directory($directory);


At the moment it requires the directory to be specified in the file. Is there anyway to make this faster, its pretty fast at the moment but I am sure it can be slightly faster, in the end I am going to be making a Backup Program for a directory so it needs to be as fast as possible.

Also any feedback on what you think of my first program done without a book would be nice thanks in advance :)

Whiteknight
12-09-2004, 07:54 PM
well, in a linux system there is a relatively good solution ( i dont know if it works the same in windows). glob all the files together, and then go through the list, performing a file test on each file (in linux, directories get counted as files, this is the part that I'm not sure windows emulates) to see if it is a directory.

If it is a directory, perform a recursive call on the function, to open the sub-directory, and start from the top. Whenever there are no more directories to open and explore, close and return from the function.

in this way, you will get into every directory, although there will be a good amount of overhead from all the recursive function calls.