简体   繁体   中英

Store the list of directories in an array

I received a Perl script which currently reads a list of directories from a text file and stores them in a string vector. I would like to modify it so that it reads the names of all the directories in the current folder, and stores them in the vector. This way, the user doesn't have to modify the input file each time the list of directories in the current folder changes.

I have no knowledge of Perl, apart from the fact that it looks like array indices in Perl start from 0 (as in Python). I have a basic knowledge of bash and Python, but I'd rather not rewrite the script from scratch in Python. It's a long, complex script, and I'm not sure I'd be able to rewrite it in Python. Can you help me? Here is the part of the script which is currently reading the text file:

#!/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 I think the script is rather self-explanatory, but just to be sure, this piece opens a text file called "files.txt", skips a line, reads the number of directories, skips another line and reads, one name for each line, the names of all the directories in the current folder, as written in "files.txt".

EDIT I wrote this script following @Sobrique suggestion, but it lists also files, not only dirs:

#!/usr/bin/perl
use Cwd;

my @flow = glob ("*");

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

It's simpler than you think:

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

If you want to filter by a criteria - like 'is it a directory' you can:

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

Open directory inside which the sub-directories are with 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);

Since readdir returns bare names we need to prepend the path.

You can also get dir like this:

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
'
        ];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM