How can I read a directory in Perl with one statement?

I am writing a script that searches for specific files in a directory and processes them. I continue to write the following:

opendir DIR, $dir;
@files = readdir DIR;
closedir DIR;

While I could (and really should) wrap this in a function, I was wondering if there is a more elegant way to do this?

+3
source share
5 answers

The most elegant is to use a function that someone else wrote.

use File::Slurp;

@files = read_dir $dir;  # . and .. are removed by default
+14
source

Another way would be to use a block do:

my @files = do {
    opendir my $d, '/your/dir/';
    readdir $d;
};

, $d ( DIR ), , , $d .

/I3az/

+5
+1

glob? , :

@files = glob("$dir/*");

, , , :

@files = glob("$dir/{.,}*")
0

glob - . , , , .

0

Source: https://habr.com/ru/post/1720059/


All Articles