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

Hi,

When I use "opendir" to open a directory, I can get all the file names in that directory by using "readdir". But how can I get the names of the sub-directories, and store them into variables?

Thank you.

  • Comment on How to get the names of sub-directory in a directory?

Replies are listed 'Best First'.
Re: How to get the names of sub-directory in a directory?
by Kanji (Parson) on Feb 01, 2002 at 13:28 UTC

    If you only want the immediate sub-directories, you can use grep and -d on the entries returned to work out what they are, using the handy (and easily adapted) example from readdir's perldoc entry.

    opendir(DIR, $some_dir) || die "Can't opendir $some_dir: $!"; @subdirs = grep { -d "$some_dir/$_" } readdir(DIR); closedir DIR;

    If you want all the sub-directories (including the sub-directories of sub-directories), then you probably want to take a look at File::Find instead.

        --k.


Re: How to get the names of sub-directory in a directory?
by strat (Canon) on Feb 01, 2002 at 13:33 UTC
    If you even want to filter . and .., you could use something like the following:
    opendir(DIR, $some_dir) or die "Can't opendir $some_dir: $!"; my @subdirs = (); foreach (readdir(DIR)){ next if /^\.\.?$/; # skip . and .. push (@subdirs, $_) if -d "$some_dir/$_"; } closedir DIR;

    Best regards,
    perl -e "$_=*F=>y~\*martinF~stronat~=>s~[^\w]~~g=>chop,print"

      I'll side with merlyn here. Do not use /^\.\.?$/, but rather /^\.\.?\z/, and if you need to know the difference, re-read the regex docs on how the $ and \z anchors differ.

      _____________________________________________________
      Jeff[japhy]Pinyan: Perl, regex, and perl hacker.
      s++=END;++y(;-P)}y js++=;shajsj<++y(p-q)}?print:??;

Re: How to get the names of sub-directory in a directory?
by tachyon (Chancellor) on Feb 01, 2002 at 13:42 UTC

    -d is the directory file test operator, see perlman:perlfunc and search for -X

    #usr/bin/perl -w use strict; my $root = 'c:/'; my @subdirs; opendir DIR, $root or die "Oops $!\n"; while (my $file = readdir DIR) { push @subdirs, $root.$file if -d $root.$file;; } print "The subdirs of $root are:\n"; print "$_\n" for @subdirs;

    cheers

    tachyon

    s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print

Re: How to get the names of sub-directory in a directory?
by George_Sherston (Vicar) on Feb 01, 2002 at 15:04 UTC