in reply to recursive directory question

G'day Aquilo

In the interests of explaining what is wrong with your code I've written a point by point summary of various lines of your code. Like merlyn I like the problem, and I hope that my advice here may be of help. I must say though that merlyn's solution or any other solution that uses File::Find is guaranteed to be better than the improvements I suggest to your code.

Some of these points may be too pedantic. Please forgive them if so.

So, I've identified a bunch of areas for improvement in your code. Here is one of the many ways your code could be rewritten to fit your requirements.
#!/usr/bin/perl -w use strict; my $path "./"; my @oldies = recurse_dirs($path); print "These directories have more files unused than used: \n". join("\n", @oldies), "\n"; sub recurse_dirs { my ($path) = @_; # make sure we're dealing with a directory return () unless(-d "$path"); my $used_recently = 0; my $unused = 0; my @old; my $now = time(); my $max_age = 180*24*60*60; # Open the directory, read each file in. opendir(DIRECTORY, $path) or die "Cannot open directory $path\ +n"; foreach my $file (readdir(DIRECTORY)) { # we don't want . or .. next if $file eq "." or $file eq ".."; # skip if this is a symbolic link. next if -l "$path/$file"; # it's a directory. Note that by pushing the # returned list on to our list we don't accide +ntly # clobber previous values if(-d "$path/$file") { push @old, recurse_dirs("$path/$file"); next; } # it's not a directory, so find out it's last # access time. my $last_access = (stat("$path/$file"))[8]; # increment accordingly if(($now - $last_access) > $max_age) { $unused++; # not used recently } else { $used_recently++; # used recently } } close(DIRECTORY); # There are more unused files than used recently if($unused > $used_recently) { push @old, $path; } return @old; }

Of course, doing it all by hand is nowhere near as fast as getting that lovely module File::Find to do it for you, so use merlyn's solution in preference to this.

Hope it helps.

jarich

Update: Added test for symbolic link, as per Aristotle's reminder. I'm sure there are more gotchas here.

Replies are listed 'Best First'.
Re^2: recursive directory question
by Aristotle (Chancellor) on Jul 08, 2002 at 13:25 UTC
    Careful.. you do not test for symlinks. Do an ln -s . snaretrap and watch the code recurse forever. That is another (and more important) reason to rely on File::Find - it correctly treats all the gotchas that can come up when traversing directories.

    Makeshifts last the longest.