如何按顺序读取目录中的文件? [英] How can I read the files in a directory in sorted order?

查看:431
本文介绍了如何按顺序读取目录中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Perl中使用opendirreaddirclosedir读取目录时,readdir函数似乎并没有以任何特定的顺序读取文件(据我所知).

我正在读取一个目录,该目录包含以纪元时间戳命名的子目录:

1224161460
1228324260
1229698140

我想按数字顺序读取这些目录,这会将最早的目录放在第一位.

当我使用readdir时,它读取的第一个是1228324260,它是中间的.我知道我可以将目录内容放入数组中并对数组进行排序,但是我可以传递给readdir以按排序顺序读取的选项吗?或者,也许比将所有内容都放入数组并对数组进行排序更完美的方法来完成此任务?可能也有模块可以执行此操作,但是很难在我们的环境中安装模块,因此,除非它是内置模块,否则我不希望使用模块...

谢谢!

编辑 根据要求,我正在发布我正在使用的代码:

opendir( my $data_dh, $data_dir ) or die "Cannot open $data_dir\n";
while ( my $name = readdir($data_dh) ) {
    next if ( $name eq '.' or $name eq '..' );
    my $full_path = "${data_dir}/${name}";
    next unless ( -d $full_path );
    process_dir($full_path);
}
closedir($data_dh);

可以在数组上下文中调用

解决方案

readdir ,因此只需执行以下操作:

opendir( my $data_dh, $data_dir) or die "Cannot open $data_dir\n";
my @files = sort { $a <=> $b } readdir($data_dh);
while ( my $name = shift @files ) {
...

When I read a directory in Perl with opendir, readdir, and closedir, the readdir function doesn't seem to read the files in any specific order (that I can tell).

I am reading a directory that has subdirectories named by epoch timestamp:

1224161460
1228324260
1229698140

I want to read in these directories in numerical order, which would put the oldest directories first.

When I use readdir, the first one it reads is 1228324260, which is the middle one. I know I could put the directory contents in an array and sort the array, but is there an option I can pass to readdir to read in sorted order? Or maybe a more elegant way of accomplishing this than pushing everything into array and sorting the array? There are probably modules out there to do this too, but it is difficult to get modules installed in our environment, so unless it is a built-in module I'd prefer to not use modules...

Thanks!

EDIT As requested, I am posting the code that I am using:

opendir( my $data_dh, $data_dir ) or die "Cannot open $data_dir\n";
while ( my $name = readdir($data_dh) ) {
    next if ( $name eq '.' or $name eq '..' );
    my $full_path = "${data_dir}/${name}";
    next unless ( -d $full_path );
    process_dir($full_path);
}
closedir($data_dh);

解决方案

readdir can be called in array context, so just do this:

opendir( my $data_dh, $data_dir) or die "Cannot open $data_dir\n";
my @files = sort { $a <=> $b } readdir($data_dh);
while ( my $name = shift @files ) {
...

这篇关于如何按顺序读取目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆