[ACCEPTED]-Getting the list of subdirectories (only top level) in a directory using Perl-perl

Accepted answer
Score: 12

If you want to collect the dirs into an 2 array:

my @dirs = grep {-d "$root/$_" && ! /^\.{1,2}$/} readdir($dh);

If you really just want to print the 1 dirs, you can do:

print "$_\n" foreach grep {-d "$root/$_" && ! /^\.{1,2}$/} readdir($dh);
Score: 9
next unless $name =~ /^\.\.?+$/;

Also, the module File::Find::Rule makes 1 a vary nice interface for this type of thing.

use File::Find::Rule;

my @dirs = File::Find::Rule->new
    ->directory
    ->in($root)
    ->maxdepth(1)
    ->not(File::Find::Rule->new->name(qr/^\.\.?$/);
Score: 4

Just modify your check to see when $name 1 is equal to '.' or '..' and skip the entry.

Score: 1

File::Slurp read_dir automatically excludes the special dot 4 directories (. and ..) for you. There 3 is no need for you to explicitly get rid 2 of them. It also performs checking on opening 1 your directory:

use warnings;
use strict;
use File::Slurp qw(read_dir);

my $root = 'mydirectoryname';
for my $dir (grep { -d "$root/$_" } read_dir($root)) {
    print "$dir\n";
}
Score: 0
use warnings;
use strict;

my $root = "mydirectoryname";

opendir my $dh, $root
  or die "$0: opendir: $!";

while (defined(my $name = readdir $dh)) {
  next unless -d "$root/$name";
  next if $file eq ".";
  next if $file eq "..";
  print "$name\n";
}

0

More Related questions