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

I'm putting together a web server utility that needs to read ONLY directories - not files (.html, etc.) However, when I run the following snippet of code it gives me all the files - subdirectories, .html, .cgi, etc. How can I get this to only add directories to @dirs?
#!/usr/bin/perl

    my @dirs;
    my $sth;
    my $gt;

my $dir = '/home/vendors/test/public_html';

    opendir D,$dir;
    @dirs=grep(!-d, readdir D);
    closedir D;

foreach (sort @dirs) {print "$_\n"};

Replies are listed 'Best First'.
Re: Regex and perl directories question
by mkmcconn (Chaplain) on Nov 20, 2001 at 04:31 UTC
    Something like this, I think:
    #!/usr/bin/perl my @dirs; my $sth; my $gt; my $dir = '/home/vendors/test/public_html'; opendir D,$dir or die $! chdir $dir; @dirs=grep{-d} readdir D; closedir D; foreach (sort @dirs) {print "$_\n"};
    Maybe, although short, grep is not the best way to do this.
    (# my @dirs = grep (-d, readdir D); # would work just as well, of course).
    mkmcconn
      Thanks for your help!

      bjdevil
Re: Regex and perl directories question
by growlf (Pilgrim) on Nov 20, 2001 at 04:38 UTC
    Try something more like this:
    #!/usr/bin/perl -w my @dirs; my $sth; my $gt; my $dir ='/home/vendors/test/public_html'; opendir(D,$dir); @dirs=grep( -d "$dir/$_" , readdir(D)) ; closedir D; foreach (sort @dirs) {print "$_\n"};


    *G*