Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Re: Win32 Recursive Directory Listing

by tachyon (Chancellor)
on Apr 09, 2002 at 20:53 UTC ( [id://157851] : note . print w/replies, xml ) Need Help??

in reply to Win32 Recursive Directory Listing

OK I like to know how things work so although you can and probably should do this with a module here is how you roll your own (without even needing recursion)

#!/usr/bin/perl -w use strict; my $root = 'c:/winnt/'; my @dirs = ($root); my @files; for my $path (@dirs){ opendir ( DIR, $path ) or next; # skip dirs we can't read while (my $file = readdir DIR) { next if $file eq '.' or $file eq '..'; # skip dot files next if -l $path.$file; # skip sym links if ( -d $path.$file ) { push @dirs, $path.$file.'/'; # add dir to list } else { push @files, $path.$file; # add file to list } } closedir DIR; } print "Directory list\n\n"; print "$_\n" for sort @dirs; print "\n\nFile List\n\n"; print "$_\n" for sort @files;

How we do it is simple. First we define our root dir and our delimiter and push this into the @dirs array. We then iterate over the @dirs array. Although @dirs initially only contains the root dir we find all its subdirs and push them onto the end of this. Thus after the first iteration @dirs contains all the subdirs of our root dir which we then search for subdirs and so on ad infinitum until we have no more subdirs. Testing for the . and .. dirs is important as these are the current and one level up dirs. We do not want to follow symbolic links otherwise we may end up in an infinite loop.

We then test each 'file' to see if it is a direcory or a file and push it into the appropriate array. By the fime we have iterated over @dirs we have root and all it subdirectories (to whatever depth) in @dirs and all the files in @files. These are the fully qualified paths.

Hope this helps.