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

Probably something along these lines:

my $dir = 'directory name goes here'; my @files = <$dir/*>; my $count = @files;
--

See the Copyright notice on my home node.

"The first rule of Perl club is you do not talk about Perl club." -- Chip Salzenberg

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

    Nit-picking: the dot files (like ".bashrc") are not counted when using the glob.

      is it efficient with more than 100 000 files in the directory ? if I well understand the code, each inode is loaded in memory... so do you know another mean to get this count, without need of a huge memory ?
      That depends on your shells. At least under bash, you can use glob() to grab dot files, for example:
        print "$_\n" for grep{ -f } glob(".*");
      
      Or probably if you want to grab both dot and non-dot files:
        print "$_\n" for grep{ -f } glob("{*,}.*");
      
      Regards,
      Xicheng

        Nope. It does not depend on your shell. At least not if you're using Perl 5.6 or later, because glob is implemented via the standard File::Glob extension and does not rely on shell anymore.

        The standard behavior of <*> or glob('*') is to not consider the dot files.

Re^2: quickest way to find number of files in a directory?
by ikegami (Patriarch) on Mar 27, 2007 at 17:47 UTC
    That also fails if $dir contains spaces or other glob meta characters.
Re^2: quickest way to find number of files in a directory?
by Anonymous Monk on Mar 27, 2007 at 17:25 UTC
    That works very nicely, thank you.
      Some people use whitespaces in paths. Try: my @files = <'$dir/*'>;
Re^2: quickest way to find number of files in a directory?
by zoroaster (Initiate) on Jul 01, 2012 at 22:10 UTC
    Thanks a lot, that works great. Does anybody know if it's possible to include variables in the file handle? For example, if I want all the .pl files starting with 'blabla' is it possible to do something like this: my $prename = 'blabla'; my @files = <$prename*.pl> my $count = @files It works with just <*.pl> but I can't get the variable to work.
        Yes, it was mistake on my part - it works with variables, too. Sorry about that.