I usually use something like
my $dir="/path/to/dir";
opendir(DIR, $dir) or die "can't open $dir: $!";
my @files = readdir DIR;
closedir DIR;
or sometimes I use glob
, but anyway, I always need to add a line or two to filter out .
and ..
which is quite annoying.
How do you usually go about this common task?
When I just want the files (as opposed to directories), I use grep
with a -f
test:
my @files = grep { -f } readdir $dir;
I often use File::Slurp. Benefits include: (1) Dies automatically if the directory does not exist. (2) Excludes .
and ..
by default. It's behavior is like readdir
in that it does not return the full paths.
use File::Slurp qw(read_dir);
my $dir = '/path/to/dir';
my @contents = read_dir($dir);
Another useful module is File::Util, which provides many options when reading a directory. For example:
use File::Util;
my $dir = '/path/to/dir';
my $fu = File::Util->new;
my @contents = $fu->list_dir( $dir, '--with-paths', '--no-fsdots' );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With