I’m very much a perl newbie, so bear with me.
I was looking for a way to recurse through folders in OS X and came across this solution: How to traverse all the files in a directory…
I modified perreal’s answer (see code below) slightly so that I could specify the search folder in an argument; i.e. I changed my @dirs = ("."); to my @dirs = ($ARGV[0]);
But for some reason this wouldn’t work — it would open the folder, but would not identify any of the subdirectories as folders, apart from ‘.’ and ‘..’, so it never actually went beyond the specified root.
If I actively specified the folder (e.g. \Volumes\foo\bar) it still doesn’t work. But, if I go back to my @dirs = ("."); and then sit in my desired folder (foo\bar) and call the script from its own folder (foo\boo\script.pl) it works fine.
Is this ‘expected’ behaviour? What am I missing?!
Many thanks,
Mat
use warnings;
use strict;
my @dirs = (".");
my %seen;
while (my $pwd = shift @dirs) {
opendir(DIR,"$pwd") or die "Cannot open $pwd\n";
my @files = readdir(DIR);
closedir(DIR);
foreach my $file (@files) {
if (-d $file and ($file !~ /^\.\.?$/) and !$seen{$file}) {
$seen{$file} = 1;
push @dirs, "$pwd/$file";
}
next if ($file !~ /\.txt$/i);
my $mtime = (stat("$pwd/$file"))[9];
print "$pwd $file $mtime";
print "\n";
}
}
The problem is that you are using the
-doperator on the file basename without its path. Perl will look in the current working directory for a directory of that name and return true if it finds one there, when it should be looking in$pwd.This solution changes
$fileto always hold the full name of the file or directory, including the path.