[Pdx-pm] recursive IO::Dir

Tom Keller kellert at ohsu.edu
Thu Feb 18 11:04:59 PST 2010


Greetings,
I need to be able to process files within a directory tree. I know there is a module IO::Dir::Recursive, but I have trouble wrapping my brain around recursion, so I wanted to give it a try just using IO::Dir. This seems to do the recursion correctly:

#!/usr/bin/perl -w
use strict;
use IO::Dir;

my $source = $ARGV[0];
my $count;

process_dir($source);
print "$count files in all.\n";

sub check {
my ($dh,$path) = @_; ## dirhandle and path
while (defined($_ = $dh->read)) {
next if m/^\.+/; ## skip dot files
if ( -f "$path/$_" ) {
my $file = "$path/$_";
process_file($file);
} elsif ( -d "$path/$_" ) {
my $dir = "$path/$_";
process_dir($dir);
} else { print "unknown thing\n"; }
}
undef $dh;
}

sub process_file {
my $file = shift;
$count++;
}

sub process_dir {
my $path = shift;
my $dh = IO::Dir->new($path);
check($dh,$path);
}

## ... I'm guessing there's a better way, so I'm asking for feedback.

thanks,

Tom
kellert at ohsu.edu<mailto:kellert at ohsu.edu>
503-494-2442







-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/pdx-pm-list/attachments/20100218/7118e9a7/attachment.html>


More information about the Pdx-pm-list mailing list