A generic directory walker in Perl
December 11, 2007 22:10:28 Last update: January 14, 2010 03:39:31
The subroutine
recurse traverses a directory tree. The function to be performed, which works on the current file with optional parameters, is passed in as a parameter.
# perl - recursive dirctory tasks # 1. recursively display all file names print "Listing all files recursively...\n"; recurse(sub { my $file = shift; print "$file\n"; }, "."); # 2. find all Java files print "\nListing all Java files recursively...\n"; recurse(sub { my ($file, $pattern) = @_; if ($file =~ /$pattern/) { print "$file\n"; } }, ".", '\.java$'); # 3. find a Java class from a directory print "\nFinding Java class...\n"; recurse(sub { my ($file, $lookfor) = @_; if ($file =~ /\.jar$/) { my @list = grep {/$lookfor/} `jar -tf $file`; if (@list) { print "$file:\n"; print join('', @list), "\n"; } } elsif ($file =~ /$lookfor/) { print "$file\n"; } }, ".", "ClassToFind"); sub recurse { my $func = shift; my $dir = shift; opendir(DIR, $dir) or die "Can't opendir $dir: $!"; my @files = map "$dir/$_", grep { !/^\.\.?$/ } readdir(DIR); closedir DIR; foreach $file (@files) { if (!-l $file && -d $file) { recurse($func, $file, @_); } else { &$func($file, @_); } } }
Easy email testing with http://www.ximailstop.com