in reply to Count folder/files in directory

use strict; use File::Find; my $source = 'c:/directory'; my $folders = 0; my $files = 0; $File::Find::dont_use_nlink = 1; # to fix a bug in File::Find File::Find::find( sub { if (-f $File::Find::name) { $files++ } elsif (-d $File::Find::name) { $folders++ }; }, $source ); print "Summary of $source\n"; print "Folders: $folders\n"; print "Files: $files\n";

Also note how my code has a different background and a "download" link. This is because I wrapped it in <code>...</code> tags instead of using <pre> tags. PRE tags are kind of frowned upon here - see the Writeup Formatting Tips for further information.

Replies are listed 'Best First'.
Re^2: Count folder/files in directory
by kyle (Abbot) on May 22, 2008 at 16:10 UTC

    The OP tries to avoid counting the "." and ".." directories. Slip a "return if /^\.\.?\z/" in at the top of that anonymous sub, and I think that's it.

      For me, File::Find does call the callback with $File::Find::name neither equal to . nor ... I would consider such behaviour buggy, myself. Not that I consider File::Find to be free of bugs, but using it beats implementing the recursive routine and worrying about meta entries returned from readdir.

      File::Find::find will only process a "." directory if that is the directory you are starting at (it also processes "." if you start at ".."). If you don't want to count the directory(s) you start from, I think the easiest thing is just to subtract the number of starting directories from the directory count.