Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi there Monks!
I am puzzled with a simple issue here (not for me I guess), I need to list all the files in a directory and print the counts, lets say in this directory are 25 files, I would print the file name and "1 of 25 file name 1", "2 of 25 file name 2" till it reaches the last file, "25 of 25 file name 25". Cant figure this one!
#!/usr/bin/perl use strict; use warnings; my $dir = "/mydir"; my $counter=0; opendir(DIR, $dir) or die $!; while (my $file = readdir(DIR)) { # just files next unless (-f "$dir/$file"); $counter++; print "$counter of $counter - $file\n"; } closedir(DIR); exit 0;
Thanks for the help!

Replies are listed 'Best First'.
Re: Counting files in directory.
by MidLifeXis (Monsignor) on Sep 22, 2011 at 18:16 UTC

    I won't give you the answer straight out (sounds a little like homework), but give you some points to consider.

    If you are using this:

    $counter++;

    what do you think this would do?

    print "$counter of $counter - $file\n";

    You will need to capture the set of directory entries (@dirs = readdir...). Then you can iterate over the set of files, using the size of the @dirs variable as your total count.

    --MidLifeXis

      my @files = <$dir/*>; my $count = @files;
      but I would like to the this counter while inside of the while loop.

        Until you finish the loop, you don't how many files are in the directory. You have to count how many files are in the directory before you can say "x is file z of z."


        Improve your skills with Modern Perl: the free book.