tags:

views:

149

answers:

6

I'm writing a script that looks for certain files in a directory and processes them. I keep on writing the following:

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

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

+13  A: 

Most elegant is to use a function someone else has already written.

use File::Slurp;

@files = read_dir $dir;  # . and .. are removed by default
Dave Hinton
+1  A: 

I like to use File::Find for this kind of thing.

Zoran Simic
Why would you want to do a depth-first search to get the list of files from one directory?
brian d foy
+4  A: 

Another way would be to use a do block:

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

Its more elegant because my $d is local to block (unlike your DIR global) and closedir isn't needed because the filehandle is automatically closed when $d went out of scope.

/I3az/

draegtun
A: 

No one has suggested glob yet? OK, here goes:

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

Or if you need files that begin with a dot, too:

@files = glob("$dir/{.,}*")
mobrule
A: 

Check IO::All.

depesz
A: 

glob is the simplest solution. I do not know what you think the first three lines belogn in a subroutine, unless you are opening the files more than once