如何按顺序读取目录中的文件?
当我在 Perl 中使用 opendir
、readdir
和 linedir
读取目录时,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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
readdir 可以在数组上下文中调用,所以只需这样做:
readdir can be called in array context, so just do this:
你可以用一点 Glob 魔法来尝试一下,glob 似乎以排序的方式运行,所以这个:
or
应该可以工作。 请小心 glob,因为这:
做了一些半神奇的事情,并在每行上打印两次 dir 内容。 IE:
You can try it with a bit of Glob magic, glob appears to function in a sorted manner, so this:
or
should work. Just be careful with glob, because this:
does something semi-magical, and prints the dir contents twice on each line. ie:
只需在要重新排序的任何列表运算符前面添加一个
sort
即可。 您也不需要将结果存储在数组中。 您可以使用foreach
:Just throw a
sort
in front of any list operator that you want to re-order. You don't need to store the results in an array either. You can use aforeach
: