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.

Replies are listed 'Best First'.
Re^2: quickest way to find number of files in a directory?
by jdporter (Paladin) on Mar 27, 2007 at 20:05 UTC

    ++ to you. That's the way to go.

    I like let handles close automatically on block exit (where feasible) and since this snippet fits naturally in a sub, I'd do this:

    sub files_in_dir { my $dir = shift || '.'; opendir my $dh, $dir or croak "opendir '$dir' - $!"; grep { -f } readdir $dh; }

    It produces the number of files if called in scalar context and the list of filenames if called in list context.

    A word spoken in Mind will reach its own level, in the objective world, by its own weight