开发者

How can I read a directory in Perl with one statement?

开发者 https://www.devze.com 2022-12-09 00:42 出处:网络
I\'m writing a script that looks for certain files in a directory and processes them.I keep on writing the following:

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?


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

use File::Slurp;

@files = read_dir $dir;  # . and .. are removed by default


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/


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


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/{.,}*")


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号