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

I am writing this program to find out the total no of subdirectories and list them in linux environment.Can anyone find out my mistake?
while(<STDIN>) { my($line) = $_; chomp($line); if($line !~ /total/) { if ($line =~ /(\w {1}).{55}(.+)$/ and $1=="d") { $count=$count+1; print "\n $2"; } } } print "Total no of directories = $count";

Edit by tye: Add code tags, remove br tags

20050219 Edit by castaway: Changed title from 'Findind total no of subdirectories and list them'

Replies are listed 'Best First'.
Re: Finding total number of subdirectories and list them
by Zaxo (Archbishop) on Feb 15, 2005 at 05:51 UTC

    What is STDIN connected to? If nothing in particular, it will read as lines whatever is typed at the console.

    Why not do this with File::Find?
    use File::Find; my $basedir = '/some/path'; my $dircount = 0; find( sub { -d && $dircount++; print $FILE::Find::name, "\n"; }, $basedir }; printf "%s subdirectories found.\n", $dircount;

    After Compline,
    Zaxo

Re: Finding total number of subdirectories and list them
by gopalr (Priest) on Feb 15, 2005 at 06:13 UTC

    I think Your coding is not right way.

    Your requirement is to get the Total no. of Sub-Directories in Specific Main Directory, use File::Find Modules.

    @ARGV = 'c:/temp/'; use File::Find (); $dircount=0; sub find(&@) { &File::Find::find } *name = *File::Find::name; find { if (-d $name) { $dircount++; print "\n$name"; } } @ARGV; print "\nTotal No. of Sub-Directories = $dircount";
Re: Finding total number of subdirectories and list them
by atcroft (Abbot) on Feb 15, 2005 at 05:45 UTC

    At the risk of offering a shell-based answer (replace '.' with desired directory, add '-mindepth 1' to the find command to remove the current directory):

    find . -type d | wc -l # Number of directories find . -type d | sort # Sorted listing of subdirectories

    Another method, using perl (directories passed in via @ARGV):

    #!/usr/bin/perl use strict; use vars qw(@directories); use warnings; use File::Find; foreach my $dir (@ARGV) { find(\&wanted, $dir); } print "Count of directories: ", scalar(@directories), "\n"; print "Directories:\n"; foreach my $dir (sort @directories) { print "\t", $dir, "\n"; } sub wanted { -d && push(@directories, $File::Find::name); }