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

How do I get the names of all the subdirectories in a folder?
  • Comment on How to list all the subdirectories in a directory

Replies are listed 'Best First'.
Re: How to list all the subdirectories in a directory
by kennethk (Abbot) on Aug 19, 2009 at 17:14 UTC
    You can accomplish this by determining the contents of the directory (opendir, readdir, closedir) combined with the -d file test (-X). If you run into difficulties, post some code and we'll help you debug.

    Lightly modified from readdir:

    opendir(my $dh, $some_dir) or die "can't opendir $some_dir: $!"; my @subdir = grep { /^[^.]/ && -d "$some_dir/$_" } readdir($dh); closedir $dh;

    Update:As JavaFan points out below, note the above code excludes any directory starting with a '.'. Seems reasonable to me since those are 'invisible' under most operations and your intent/spec is not explicit, but removing the regular expression from the grep test will remove the condition.

      I'm curious why you exclude all directories starting with a dot. Sure, that excludes '.' and '..' (a case could be made to exclude them), but it also excludes directories like .git.
Re: How to list all the subdirectories in a directory
by toolic (Bishop) on Aug 19, 2009 at 17:34 UTC
Re: How to list all the subdirectories in a directory
by ikegami (Patriarch) on Aug 19, 2009 at 17:23 UTC

    Get the contents of the folder (using readdir, for example) and use -d to find out if a file is really a directory.

    You could also use a module such as File::Find::Rule, but such modules search recursively by default. You'll need to limit the depth of the search.

Re: How to list all the subdirectories in a directory
by Your Mother (Archbishop) on Aug 19, 2009 at 17:25 UTC

    Path::Class to the rescue! Or to the usage...?

    my $parent = Path::Class::Dir->new("/some/dir/path"); my @sub_dirs = grep { $_->is_dir } $parent->children;
Re: How to list all the subdirectories in a directory
by Anonymous Monk on Aug 20, 2009 at 01:22 UTC
Re: How to list all the subdirectories in a directory
by sanku (Beadle) on Aug 21, 2009 at 10:21 UTC
    hi, <code> print `ls -lthr | grep ^d`; or system ("ls -lthr | grep ^d"); The above command will list all the sub directories. --Look for and find opportunities where others see nothing