开发者

Getting the list of subdirectories (only top level) in a directory using Perl

I would like to run a perl script to find only the subdirectories in a directory. I would not like to have the "." and ".." returned.

The program I am trying to use looks like this:

use warnings;
use strict;

my $root = "mydirectoryname";

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

while (defined(my $name = readdir $dh)) {
  next unless开发者_Go百科 -d "$root/$name";
  print "$name\n";
}

The output of this however, has the "." and "..". How do I exclude them from the list?


If you want to collect the dirs into an array:

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

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

print "$_\n" foreach grep {-d "$root/$_" && ! /^\.{1,2}$/} readdir($dh);


next unless $name =~ /^\.\.?+$/;

Also, the module File::Find::Rule makes 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/^\.\.?$/);


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


File::Slurp read_dir automatically excludes the special dot directories (. and ..) for you. There is no need for you to explicitly get rid of them. It also performs checking on opening 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";
}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜