Perl でディレクトリの内容を読み取るにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/22566

  •  09-06-2019
  •  | 
  •  

質問

Perl で指定されたディレクトリの内容を配列に読み込むにはどうすればよいですか?

バッククォート はできますが、「scandir」または類似の用語を使用する方法はありますか?

役に立ちましたか?

解決

opendir(D, "/path/to/directory") || die "Can't open directory: $!\n";
while (my $f = readdir(D)) {
    print "\$f = $f\n";
}
closedir(D);

編集:ああ、申し訳ありませんが、「配列へ」の部分を見逃していました。

my $d = shift;

opendir(D, "$d") || die "Can't open directory $d: $!\n";
my @list = readdir(D);
closedir(D);

foreach my $f (@list) {
    print "\$f = $f\n";
}

編集2:他の回答のほとんどは有効ですが、コメントしたいと思いました この答え 具体的には、このソリューションが提供されるのは次のとおりです。

opendir(DIR, $somedir) || die "Can't open directory $somedir: $!";
@dots = grep { (!/^\./) && -f "$somedir/$_" } readdir(DIR);
closedir DIR;

まず、投稿者が行っていないことを文書化します。から返されたリストを渡しています readdir() を通して grep() これは、(ディレクトリ、デバイス、名前付きパイプなどではなく) ファイルであり、ドットで始まらない値 (これによりリスト名が作成されます) のみを返します。 @dots 誤解を招きますが、これは彼が readdir() ドキュメントからコピーしたときに加えた変更によるものです)。これは返されるディレクトリの内容を制限するため、技術的にはこの質問に対する正しい答えではないと思いますが、ファイル名をフィルタリングするために使用される一般的なイディオムを示しています。 パール, 、文書化する価値があると思いました。よく見られる別の例は次のとおりです。

@list = grep !/^\.\.?$/, readdir(D);

このスニペットは、ディレクトリ ハンドル D からすべてのコンテンツを読み取ります。 を除外する '.' と '..' は、リストで使用することが非常にまれであるためです。

他のヒント

手っ取り早く汚い解決策は次のとおりです。 グロブ

@files = glob ('/path/to/dir/*');

IO::ディレクトリ これは優れており、結合されたハッシュ インターフェイスも提供します。

perldoc から:

use IO::Dir;
$d = IO::Dir->new(".");
if (defined $d) {
    while (defined($_ = $d->read)) { something($_); }
    $d->rewind;
    while (defined($_ = $d->read)) { something_else($_); }
    undef $d;
}

tie %dir, 'IO::Dir', ".";
foreach (keys %dir) {
    print $_, " " , $dir{$_}->size,"\n";
}

したがって、次のようなことができます。

tie %dir, 'IO::Dir', $directory_name;
my @dirs = keys %dir;

これは 1 行で実行されます (末尾の「*」ワイルドカードに注意してください)。

@files = </path/to/directory/*>;
# To demonstrate:
print join(", ", @files);

使用できます ディレクトリハンドル:

use DirHandle;
$d = new DirHandle ".";
if (defined $d)
{
    while (defined($_ = $d->read)) { something($_); }
    $d->rewind;
    while (defined($_ = $d->read)) { something_else($_); }
    undef $d;
}

DirHandle に代わる、よりクリーンなインターフェースを提供します。 opendir(), closedir(), readdir(), 、 そして rewinddir() 機能。

これは、ディレクトリ構造を再帰的に実行し、私が作成したバックアップ スクリプトからファイルをコピーする例です。

sub copy_directory {
my ($source, $dest) = @_;
my $start = time;

# get the contents of the directory.
opendir(D, $source);
my @f = readdir(D);
closedir(D);

# recurse through the directory structure and copy files.
foreach my $file (@f) {
    # Setup the full path to the source and dest files.
    my $filename = $source . "\\" . $file;
    my $destfile = $dest . "\\" . $file;

    # get the file info for the 2 files.
    my $sourceInfo = stat( $filename );
    my $destInfo = stat( $destfile );

    # make sure the destinatin directory exists.
    mkdir( $dest, 0777 );

    if ($file eq '.' || $file eq '..') {
    } elsif (-d $filename) { # if it's a directory then recurse into it.
        #print "entering $filename\n";
        copy_directory($filename, $destfile); 
    } else { 
        # Only backup the file if it has been created/modified since the last backup 
        if( (not -e $destfile) || ($sourceInfo->mtime > $destInfo->mtime ) ) {
            #print $filename . " -> " . $destfile . "\n";
            copy( $filename, $destfile ) or print "Error copying $filename: $!\n";
        } 
    } 
}

print "$source copied in " . (time - $start) . " seconds.\n";       
}

上記と似ていますが、「perldoc -f readdir」の (わずかに変更された) バージョンが最良だと思います。

opendir(DIR, $somedir) || die "can't opendir $somedir: $!";
@dots = grep { (!/^\./) && -f "$somedir/$_" } readdir(DIR);
closedir DIR;

から: http://perlmeme.org/faqs/file_io/directory_listing.html

#!/usr/bin/perl
use strict;
use warnings;

my $directory = '/tmp';

opendir (DIR, $directory) or die $!;

while (my $file = readdir(DIR)) {
    next if ($file =~ m/^\./);
    print "$file\n";
}

次の例 (perldoc -f readdir のコード サンプルに基づく) は、開いているディレクトリからピリオドで始まるすべてのファイル (ディレクトリではない) を取得します。ファイル名は配列 @dots にあります。

#!/usr/bin/perl

use strict;
use warnings;

my $dir = '/tmp';

opendir(DIR, $dir) or die $!;

my @dots 
    = grep { 
        /^\./             # Begins with a period
    && -f "$dir/$_"   # and is a file
} readdir(DIR);

# Loop through the array printing out the filenames
foreach my $file (@dots) {
    print "$file\n";
}

closedir(DIR);
exit 0;


closedir(DIR);
exit 0;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top