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

how can get a number of the total amount of files in a directory?
i would have to subtract two from that total, if i didn't want to count the current directory and the parent directory things wouldn't i?

Replies are listed 'Best First'.
Re: Total Files
by petdance (Parson) on Jun 07, 2001 at 22:35 UTC
    Most straightforward approach would be:
    my @filelist = <*>; my $nfiles = scalar @filelist;
    You may also want to look into the readdir function.

    xoxo,
    Andy

    %_=split/;/,".;;n;u;e;ot;t;her;c; ".   #   Andy Lester
    'Perl ;@; a;a;j;m;er;y;t;p;n;d;s;o;'.  #   http://petdance.com
    "hack";print map delete$_{$_},split//,q<   andy@petdance.com   >
    
      If he just wants the number of files, why the array first?
      my $nfiles = scalar grep -f, glob("*");

      ar0n ]

        If he just wants the number of files, why the array first?

        Because someone who's new enough to not know how to get the number of files in a directory could probably use the benefit of having it spelled out in two distinct steps.

        Not everything in Perl is a matter of golf.

        xoxo,
        Andy

        %_=split/;/,".;;n;u;e;ot;t;her;c; ".   #   Andy Lester
        'Perl ;@; a;a;j;m;er;y;t;p;n;d;s;o;'.  #   http://petdance.com
        "hack";print map delete$_{$_},split//,q<   andy@petdance.com   >
        
Re: Total Files
by the_slycer (Chaplain) on Jun 07, 2001 at 22:42 UTC
    Assuming that you know how to opendir and readdir you just have to test whether it's a file or not with the -f operator. eg:
    opendir (D,".")|| die "nope sorry"; for (readdir(D)){ ++$count if -f; } print $count;
      here's a different twist. at first i thought map was a good fit for this.... merlyn has helped me learn to love map.
      opendir D,'.' or die "opendir: $!\n"; print((map{$i+=!-f}readdir(D))-$i);
      of course, for a newbie, this isn't appropriate as is, since without temp variables it's a little hard to understand.
      i just thought i'd post it because i prefer opendir and readdir, and i love map.

      =Particle

Re: Total Files
by Eradicatore (Monk) on Jun 07, 2001 at 22:37 UTC
    #!/usr/local/bin/perl -w @files = glob("*"); $i = 0; foreach $f (@files) { if (-f $f) {$i++} } print "num plain files: $i\n";

    Justin Eltoft

    "If at all god's gaze upon us falls, its with a mischievous grin, look at him" -- Dave Matthews

Re: Total Files
by wog (Curate) on Jun 07, 2001 at 22:41 UTC

    Without putting all the filenames into memory:

    opendir DIR, "somedirectory" or die "opendir: $!\n"; my $count; !/\A\.\.?\z/ && $count++ while defined($_ = readdir(DIR)); closedir DIR or warn "closedir: $!\n"; print "$count\n";

    (You'd need to add a -f or similar test for it to only consider plain files, or non-directories, etc.)