如何在Perl中读入目录的内容?

70gysomp  于 2022-11-15  发布在  Perl
关注(0)|答案(9)|浏览(173)

如何让Perl将给定目录的内容读入数组?
Backticks可以做到这一点,但有没有一些方法使用'scandir'或类似的术语?

xa9qqrwz

xa9qqrwz1#

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()grep()只返回文件类型的值(与目录、设备、命名管道等相对),并且不以点开始(这使得列表名称@dots容易引起误解,但这是由于他在从readdir()文档复制时所做的更改)。由于它限制了返回的目录的内容,我不认为这是这个问题的正确答案,但它说明了一个常见的习惯用法,用于过滤Perl中的文件名,我认为这将是有价值的文档。另一个常见的例子是:

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

这个代码片段读取目录句柄D中的所有内容,除了'.'和'..',因为这些内容很少需要在清单中使用。

deyfvvtc

deyfvvtc2#

一个快速而又不太常用的解决方案是使用glob

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

twh00eeo3#

这将在一行中完成(注意末尾的通配符“*”)

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

dvtswwa34#

IO::Dir很不错,还提供了一个绑定的哈希接口。
来自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;
gc0ot86w

gc0ot86w5#

您可以使用DirHandle

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

DirHandleopendir()closedir()readdir()rewinddir()函数提供了一个替代的、更简洁的接口。

pbgvytdp

pbgvytdp6#

与上面的类似,但我认为最好的版本是(稍微修改)从“perldoc -f readdir”:

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

aemubtdh7#

您还可以使用流行的Path::Tiny模块中的children方法:

use Path::Tiny;
my @files = path("/path/to/dir")->children;

这将创建一个Path::Tiny对象数组,如果您想对文件执行操作,这些对象通常比文件名更有用,但如果您只需要名称:

my @files = map { $_->stringify } path("/path/to/dir")->children;
gdx19jrr

gdx19jrr8#

下面是一个递归目录结构并从我编写的备份脚本中复制文件的示例。

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";       
}
r3i60tvu

r3i60tvu9#

从: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;

相关问题