traversing directory trees in perl
Thursday, March 24th, 2005I spent a whole day trying to traverse a directory tree using Perl, and grab all the directories that met certain criteria, and put them in an array. It sounds relatively simple, but it isn’t, and I got pretty frustrated. Finally I went to Google and typed in “perl traverse directory tree”. The first link that came up took me here. Lo and behold there is already a Perl module that will do it. The link has the info, but I still had to figure out how to use it for my own purposes. Here is some sample code that puts it into practice:
use File::Find;
sub traverse {
$options{’wanted’} = &wanted; # this option specifies a subroutine to process the results.
$options{’no_chdir’} = 1; # this option tells the module to not change the current default directory.
# there are many more options described in the link above.
find(%options, @accounts); # this command traverses the directories listed in the @accounts array.
# now you have a list of all the traversed directories, do what you want
foreach $dir (@directories) {
&doDirectory ($dir);
}
sub wanted {
local($file) = $File::Find::name;
if ( $file =~ /^\\./ ) { return; } # get rid of files or directories that begin with a period.
if ( (-d $File::Find::name) ) { # just grab directories, not files.
push @directories, $File::Find::name; # put them in an array.
}
That’s all there is to it.