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

How can I find out how many files and direcotries are in a direcotry and how can I print out an error if there is no files, and also for direcotries.

2002-07-06 Edit by Corion : Changed title

  • Comment on Finding files and subdirectories in a directory (was: A couple of ?'s)

Replies are listed 'Best First'.
Re: A couple of ?'s
by DamnDirtyApe (Curate) on Jul 06, 2002 at 03:37 UTC

    Take a look at opendir and readdir, or File::Find if you want to get fancy. :-)

    Update: A code example:

    #! /usr/bin/perl use strict ; use warnings ; opendir MYDIR, '.' or die $! ; my @allfiles = grep { $_ ne '.' and $_ ne '..' } readdir MYDIR ; my @files = grep { !-d } @allfiles ; my @dirs = grep { -d } @allfiles ; print "Current directory contains " . @files . " files and " . @dirs . " directories.\n" ;

    _______________
    D a m n D i r t y A p e
    Home Node | Email
Re: A couple of ?'s
by vek (Prior) on Jul 06, 2002 at 08:20 UTC
    You need to find out how many files & directories there are? Try this out:
    opendir (THEDIR, $theDir) || die "Could not read $theDir - $!\n"; my ($filesFound, $dirsFound); for my $fileFound (readdir(THEDIR)) { next if ($fileFound eq '.' || $fileFound eq '..'); if (-d $fileFound) { # we found a directory... $dirsFound++; } else { # looks like it's a file... $filesFound++; } } if ($filesFound) { print "Found $filesFound files in $theDir.\n"; } else { print "No files were found in $theDir.\n"; } if ($dirsFound) { print "Found $dirsFound directories in $theDir.\n"; } else { print "No directories were found in $theDir.\n"; }
    -- vek --
Re: A couple of ?'s
by Anonymous Monk on Jul 06, 2002 at 04:58 UTC
    my @files = grep { !-d } @userfiles ; my @dirs = grep { -d } @userfiles ;
    Doesnt work