in reply to Gather file count in directory

For a decent number of files, you can use:
sub get_files_count { my ($dir) = @_; opendir my $dir_h, $dir or return 0; # Number of files return scalar grep { -f "$dir/$_" } readdir $dir_h; # Number of files+dirs return scalar @{[readdir $dir_h]} - 2; } print get_files_count('./');
Or for a larger number of files, you can use:
sub get_files_count { my ($dir) = @_; opendir my $dir_h, $dir or return 0; my $files = 0; while(defined(my $file = readdir $dir_h)){ if($file eq '.' or $file eq '..'){ next; } # Uncomment the bellow line to count only files # next unless -f "$dir/$file"; ++$files; } closedir $dir_h; return $files; } print get_files_count('./');

Replies are listed 'Best First'.
Re^2: Gather file count in directory
by Anonymous Monk on Jan 06, 2012 at 06:27 UTC

    I have tried this subroutine already but it takes a lot of time to count total files as disk size increases(for a drive containing 300gb used space it takes an hour to calculate the total files). I want a method which is a bit faster??