1

私は 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 モジュールを使用できる可能性があることに気付きました。

あなたが提供できるかもしれない助けをありがとう:)

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

またはfindpreprocessオプションを使用して:

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

How to Get the Last Subdirectories byliverpole on Perlmonksの質問への回答から:

現在のディレクトリの下にあるすべてのリーフ ディレクトリを出力します ( を参照"./")。

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 に答える