Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: quickest way to find number of files in a directory?

by kyle (Abbot)
on Mar 27, 2007 at 15:10 UTC ( #606769=note: print w/replies, xml ) Need Help??


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 (Canon) 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

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://606769]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2020-11-29 07:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?