Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I list all files in a directory using Perl?

Tags:

directory

perl

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?

like image 856
David B Avatar asked Sep 22 '10 17:09

David B


2 Answers

When I just want the files (as opposed to directories), I use grep with a -f test:

my @files = grep { -f } readdir $dir;
like image 81
Ether Avatar answered Sep 20 '22 04:09

Ether


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' );
like image 24
FMc Avatar answered Sep 22 '22 04:09

FMc