1

我对 Perl(一般的脚本语言)非常陌生,我想知道如何使用 Perl 来获取 Perl 中所有叶目录的列表。例如,假设我的根目录是 C:

C: -> I have folder "A" and "B" and files a.txt and b.txt

Folder "A" -> I have folder "D" and file c.html
Folder "B" -> I have folder "E" and "F" and file d.html 
Folder "D", "E" and "F" -> bunch of text files

如何获得一堆目录路径作为以下场景的输出:

C:\A\D\
C:\B\E\
C:\B\F\

如您所见,我只想列出所有可能的叶子目录。我不希望 C:\A\ 和 C:\B\ 出现。在自己进行了一些研究之后,我注意到我可能以某种方式能够在 Perl 中使用 File::Find 模块,但我也不是 100% 确定如何继续。

感谢您提供的任何帮助:)

4

3 回答 3

1

另一种方法:

use strict;
use warnings;
use feature qw( say );

use File::Find::Rule qw( );
use Path::Class      qw( dir );

my $root = dir('.')->absolute();

my @dirs = File::Find::Rule->directory->in($root);
shift(@dirs);

my @leaf_dirs;
if (@dirs) {
   my $last = shift(@dirs);
   for (@dirs) {
      push @leaf_dirs, $last if !/^\Q$last/;
      $last = $_ . "/";
   }
   push @leaf_dirs, $last;
}

say for @leaf_dirs;
于 2011-11-18T00:30:11.373 回答
1

或使用find's preprocess选项:

use strict;
use warnings;
use File::Find;

find({  wanted    =>sub{1}, # required--in version 5.8.4 at least
        preprocess=>sub{    # @_ is files in current directory
            @_ = grep { -d && !/\.{1,2}$/ } @_;
            print "$File::Find::dir\n" unless @_;
            return @_;
        }
    }, ".");
于 2011-11-18T00:57:35.880 回答
0

Perlmonks 上的liverpole 对如何获取最后一个子目录的问题的回答

打印当前目录下的所有叶目录(请参阅 参考资料"./"):

use strict;
use warnings;

my $h_dirs = terminal_subdirs("./");
my @dirs   = sort keys %$h_dirs;
print "Terminal Directories:\n", join("\n", @dirs);

sub terminal_subdirs {
    my ($top, $h_results) = @_;
    $h_results ||= { };
    opendir(my $dh, $top) or die "Arrggghhhh -- can't open '$top' ($!)\n";
    my @files = readdir($dh);
    closedir $dh;
    my $nsubdirs = 0;
    foreach my $fn (@files) {
        next if ($fn eq '.' or $fn eq '..');
        my $full = "$top/$fn";
        if (!-l $full and -d $full) {
            ++$nsubdirs;
            terminal_subdirs($full, $h_results);
        }
    }

    $nsubdirs or $h_results->{$top} = 1;
    return $h_results;
}
于 2011-11-17T23:40:17.670 回答