3

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?

Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319

5 Answers5

14

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

use File::Slurp;

@files = read_dir $dir;  # . and .. are removed by default
dave4420
  • 46,404
  • 6
  • 118
  • 152
5

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
  • 22,441
  • 5
  • 48
  • 71
1

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

Zoran Simic
  • 10,293
  • 6
  • 33
  • 35
0

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/{.,}*")
mob
  • 117,087
  • 18
  • 149
  • 283
0

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