in reply to how to get total numbers of files in a directory?

As stated in perldoc perlport it's better to not use globbing, instead use opendir.

code-example (untested) for your issue would be:
opendir(DIR, '/home/a') or die "couldn't opendir /home/a: $!"; while (local $_ = readdir(DIR)) { next unless $_ =~ /\.txt$/; print "$_\n"; } closedir(DIR) or die "couldn't close /home/a: $!";
greetings

Replies are listed 'Best First'.
Re: Re: how to get total numbers of files in a directory?
by mpeppler (Vicar) on Dec 09, 2003 at 15:50 UTC
    I'd have written that as
    opendir(DIR, "/home/a") || die "can't open dir: $!"; my $count = grep(/\.txt$/, readdir(DIR)); closedir(DIR); print "There are $count .txt files\n";
    assuming that the only purpose is to get a count of matching files.

    Michael

      That has the disadvantage of potentially using a lot of memory if there are many files in the directory (the globbing solutions, and solutions that use readdir in list context all suffer from this).

      I would use something like:

      my $cnt = 0; local $_; chdir "/home/a" or die "chdir: $!"; opendir my $dh => "." or die "opendir: $!"; -f && /\.txt$/ && $cnt ++ while defined ($_ = readdir $dh); closedir $dh;

      Abigail

        or a simple shell script? find . -maxdepth 1 -name '*.*' | wc -l