in reply to Why does File::Find chdir?

Well, the other day I was just thinking about how I keep getting bitten on code like this:
# Find all sub-dirs of $dir opendir DIR, $dir or die "yaddah:$!"; @subdirs = grep { -d } readdir(DIR);
This simple, obvious code doesn't do what I expect. The reason is that I keep forgetting to explictly do a chdir($dir): the "-d" is looking in the wrong place. So myself, I've been wondering why an "opendir" doesn't do a "chdir" for you... You can do the recursive equivalent of that task using File::Find like so:
use File::Find; find( sub { -d && print $File::Find::name, "\n"; }, $dir );
Without the implicit "chdir" behavior, you'd need to change the "-d" line to:
-d $File::Find::name && print $File::Find::name, "\n";

Replies are listed 'Best First'.
Re^2: Why does File::Find chdir? (glob++)
by tye (Sage) on Jul 14, 2004 at 00:32 UTC

    This is one reason why I prefer glob to opendir:

    my @dirs= grep { -d } glob( "$dir/*" );

    works. It forces you to either chdir or prepend the directory name (and often makes much simpler code).

    You also forgot to filter out "." and ".." in your version. Of course, my version won't report ".cpan" (which might be a bug or a feature, depending), and I wish glob provided an option to make that trivial to do.

    - tye