Perl readdir as one-liner?
At the moment, I know of two ways to open and read a directory in Perl. You can use opendir
, readdir
and closedir
or just use glob
to get the contents of the directory.
Example:
Using opendir
, readdir
and closedir
:
opendir my $dh, $directory;
my @contents = readdir $dh;
closedir $dh;
Usage glob
:
my @contents = <$directory/*>;
I have been advised that the method glob
can give unpredictable results in some situations (for example, it can act differently on different operating systems when it encounters special characters in directory names).
What I love about the method glob
is that it's "quick and dirty". It's one simple line, and it gets the job done, but if it doesn't work in all situations that can lead to unexpected and hard-to-find errors.
I was wondering if there was some sort of "shorthand" way to use the
opendir
,readdir
,closedir
method?
Maybe something like this fancy method for deleting a file in one line that I recently discovered.
source to share
How about the next one?
my @contents = get_dir_contents($dir);
You can even decide how to handle errors, if it .
should be returned, if it ..
should be returned, if "hidden" files should be returned, and whether the path will be appended to the filename since you write it get_dir_contents
yourself.
Alternative:
-
use File::Find::Rule qw( ); my @contents = File::Find::Rule->maxdepth(1)->in($dir);
-
use File::Slurp qw( read_dir ); my @contents = read_dir($dir);
-
# Unix only, but that includes cygwin and OS/X. my @contents = <\Q$dir\E/.* \Q$dir\E/*>;
source to share