We Recommend

Learning Perl Learning Perl
In this smooth, carefully paced course, a leading Perl trainer teaches you to program in the language that threatens to make C, sed, awk, and the Unix shell obsolete for many tasks. This book is the "official" guide for both formal (classroom) and informal learning. It is fully accessible to the novice programmer.


Posted By

amosshapira on 01/13/08


Tagged

file count directory perl


Versions (?)


Who likes this?

1 person has marked this snippet as a favorite

noah


Count directory entries in given directories


Published in: Perl 


In response to a very simplistic solution suggestion using Shell, here is a basic version of what I use. The advantage of the solution below is that it is supposed to be much faster on directories with many files (I regularly use its full-blown version on directories with tens and hundreds of thousands of files).

  1. #!/usr/bin/perl
  2. $ARGV[0] = '.' unless @ARGV;
  3. for my $dir (@ARGV) {
  4. opendir DIR, $dir or die "$dir: $!\n";
  5. $file =~ m:^\.: or ++$count
  6. while ($file = readdir DIR);
  7. closedir DIR;
  8. }
  9. print "$count\n";
  10. exit 0;

Report this snippet 

Comments

RSS Icon Subscribe to comments
Posted By: noah on June 17, 2008

Thanks for this -- the "simplistic solution" definitely bogs down when there's a significant number of files involved. Nice suggestion, I will try this next time I need to process a big directory tree.

You need to login to post a comment.