http://www.perlmonks.org?node_id=606769


in reply to quickest way to find number of files in a directory?

I haven't benchmarked this (with Benchmark) or anything, but a quick opendir/readdir would get it done:

my $directory_name = shift || '.'; opendir my $dh, $directory_name or die "Can't opendir '$directory_name': $!"; my $file_count = scalar grep { -f "$directory_name/$_" } readdir $dh; closedir $dh or die "Can't closedir: $!";

It's bigger and more complicated than a glob-based solution, but you get nice error messages in case there's problems.

If you're interested in all directory entries (i.e., subdirectories and not just files), you can make the grep match { !m{ \A \.\.? \z}x } instead (so it still skips "." and "..").

Updated to fix a problem helpfully pointed out by Corion. The -f needs to have the directory named explicitly in case it's not the current directory.