DeltaIV DeltaIV - 5 months ago 8
Perl Question

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

Answer

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/*";