将目录列表存储在数组中

Store the list of directories in an array

我收到了一个 Perl 脚本,它当前从文本文件中读取目录列表并将它们存储在字符串向量中。我想修改它,让它读取当前文件夹中所有目录的名称,并将它们存储在向量中。这样,用户不必在当前文件夹中的目录列表每次更改时都修改输入文件。

我对 Perl 一无所知,除了它看起来像 Perl 中的数组索引从 0 开始(如 Python)。我有 bash 和 Python 的基本知识,但我不想在 Python 中从头开始重写脚本。这是一个又长又复杂的脚本,我不确定我是否能够在 Python 中重写它。你能帮助我吗?这是当前正在读取文本文件的脚本部分:

#!/usr/bin/perl
use Cwd;
.
.
.
open FILES, "<files.txt" or die; # open input file
<FILES> or die;              # skip a comment
my $nof = <FILES> or die;    # number of directories
<FILES> or die;              # skip a comment
my @massflow;                # read directories
for (my $i = 0; $i < $nof; $i++){
    chomp($massflow[$i] = <FILES>);
}
. 
.
. 
close(FILES);

PS 我认为该脚本是不言自明的,但可以肯定的是,这篇文章打开一个名为 "files.txt" 的文本文件,跳过一行,读取目录数,跳过另一行并读取,每行一个名称,当前文件夹中所有目录的名称,如 "files.txt".

中所写

编辑我按照@Sobrique 的建议编写了这个脚本,但它还列出了文件,而不仅仅是目录:

#!/usr/bin/perl
use Cwd;

my @flow = glob ("*");

my $arrSize = @flow;
print $arrSize;
for (my $i = 0; $i < $arrSize; $i++){
    print $flow[$i], "\n";
}

比你想象的要简单:

my @list_of_files = glob ("/path/to/files/*"); 

如果您想按条件过滤 - 例如 'is it a directory' 您可以:

my @list_of_dirs = grep { -d } glob "/path/to/dirs/*"; 

打开子目录所在目录opendir, read its content with readdir. Filter out everything that is not a directory using file test -d, see -X

my $rootdir = 'top-level-directory';
opendir my $dh, "$rootdir" or die "Can't open directory $rootdir: $!";
my @dirlist = grep { -d } map { "$rootdir/$_" } readdir ($dh);

因为 readdir returns 裸名我们需要在路径前添加。

你也可以这样获取目录:

my @dir = `find . -type d`;

perl -e ' use strict; use warnings; use Data::Dumper; my @dir = `find . -type d`; print Dumper(\@dir);'

$VAR1 = [
          '.
',
          './.fonts
',
          './.mozilla
',
          './bin
',
          './.ssh
',
          './scripts
'
        ];