Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: Recursive Subdirectories

by t'mo (Pilgrim)
on Apr 18, 2003 at 05:26 UTC ( [id://251388] : note . print w/replies, xml ) Need Help??

in reply to Recursive Subdirectories

Two ideas. 1) In the spirit of TMTOWTDI ("there's more than one way to do it"), and since you're running this on Windows, why not borrow some COM objects, or more specifically, the "Scripting.FileSystemObject". 2), Really, this probelm is nothing more than a depth-first traversal of a tree; File::Find just does the traversal for you. The beauty of combining these two ideas is that you still can see what your program does (i.e., the recursive nature of the problem and solution is hidden in File::Find), but because the FileSystemObject has methods giving you either the files or the directories: you don't have to check to see whether you have a file or a directory from readdir.

The following is not unlike a WSH program I recently had to hack together...except that the Perl hasn't been tested, since (in theory) I work in a Microsoft-only shop...:

#!perl -w use strict; use Win32::OLE qw(in); # configure this for your starting directory/path my $start = "c:\\temp"; sub visit { my $file = shift; # broken!!! # ...logic here to check date of file, and print it; # just don't forget that it's a "Windows" object, not a # file descriptor or file/path or something else... #if ( $file->DateLastModified > 3 ) { print $file->name . "\n" } } my $fso = Win32::OLE->new("Scripting.FileSystemObject"); sub scan_directory { my $path = shift; print "Scanning $path...\n"; my $folder = $fso->GetFolder($path); foreach my $subdir ( in $folder->SubFolders ) { scan_directory($path . "\\" . $subdir->Name); } foreach my $file ( in $folder->Files ) { visit($file) } } scan_directory($start);

p.s. Thanks to this reference, which indirectly pointed out that I should use Win32::OLE 'in'; I was able to actually make this thing *almost* work.

...every application I have ever worked on is a glorified munger...