Saturday, August 23, 2008

Code Review Vol. 4 - Perl Recursive Directory Stepper

Here is a recursive directory browser I wrote in Perl. I later decorated it a bit and used it for a project back at Toll Brothers. The goal was to create a shared directory for the IT Training department, where trainers for each department could store their respective white papers without the admin for IT Training having to manage those documents.

So this script simply reads the contents of the shared directory and recursively steps through all folders inside and lists out all documents.


#!/usr/bin/perl

use DBI;
use CGI;


my $q = new CGI;
my $logFile = "exceptions.txt";
my $showDir= "/EASYT/TRAINING/manuals";
print $q->header( "text/html" );
peruseDir($showDir, '0');

exit(0);

sub peruseDir{
#create local copy of parameters
#second parameter of which is an indirect file handle
#so we can keep making recursive calls to peruseDir
#increment the indirect fhandle as we go so that we
#arent stuck on the same file through each iteration
local($currDir, $input) = @_;
$input++;
if($currDir !~ m/.*\..*/){
opendir($input, $currDir) || die print "Can't open $currDir $!
\n\n";
my @tempArr = grep { $_ ne '.' and $_ ne '..' } readdir($input);
foreach $myDir(@tempArr){
if(-d $currDir."/".$myDir){
#if its a directory make another recursive step
print "$input $myDir
";
peruseDir($currDir."/".$myDir, $input);
}else{
#otherwise its a file, show file
my $linkDir = $currDir;
$linkDir =~ s/\/EASYT\/TRAINING\///;
print "$myDir
";
}
}
closedir($input);
}
}


sub logExceptions{
open(LOG, ">> $logFile") || die print "Couldn't write to log $!";
foreach $exception(@_){
print LOG "$exception\n";
}
close(LOG);
}

No comments: