[Pdx-pm] recursive IO::Dir

Tkil tkil at scrye.com
Thu Feb 18 12:41:42 PST 2010


>>>>> "Tom" == Tom Keller <kellert at ohsu.edu> writes:

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

I'm amused that you did end up with recursion anyway ("process_dir"
calls "check" which can call "process_dir").  If you really want to
avoid recursion, you want to do a breadth-first search and maintain a
queue of directories to examine... but I'd advise against writing your
own directory traversal code, regardless.

One advantage to using good old File::Find is that it's available on
every perl5 install for ... gah, 15+ years now?  It also handles some
things that could trip you up if you try to write it yourself, e.g.,
symlinks that create circular loops.

Dead simple for what you want to do, too:

| #!/usr/bin/perl
| 
| use strict;
| use warnings;
| 
| use File::Find qw();
| 
| # the routine that looks at each file; for demonstration purposes,
| # it'll just give the size.  by default, File::Find::find changes into
| # each directory as goes, and $_ is just the basename.  to display the
| # full name, we use the full-qualified variable $File::Find::name.
| sub process_file
| {
|     my ( $file ) = @_;
|     print "$File::Find::name: ", ( -s $file ), " bytes\n";
| }
| 
| # assume that @ARGV holds the dirs we want to examine.
| File::Find::find( sub { process_file $_ if -f $_ },
|                   @ARGV );
| 
| exit 0;

Happy hacking,
t.


More information about the Pdx-pm-list mailing list