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 ) { ...
你可以尝试使用一些Glob魔法,glob似乎以排序的方式运行,所以这个:
# Glob in scalar context iterates the result set internally while( defined( my $dir = glob($dir . '/*' ) ) ){ print $dir, "\n"; # $dir is fed ordered and with full names. }
要么
# Glob in list context returns all results. for( glob($dir.'/*' ) ){ print $dir , "\n"; # also ordered. }
应该管用.小心使用glob,因为这样:
for(0..20){ printf "%30s|%30s\n", glob($dir.'/*' ), glob($dir.'/*' ); }
做一些半神奇的事情,并在每一行打印两次目录内容.即:
/foo/bar/a | /foo/bar/a /foo/bar/b | /foo/bar/b /foo/bar/c | /foo/bar/c /foo/bar/d | /foo/bar/d
只需sort
在要重新排序的任何列表运算符前面抛出一个.您也不需要将结果存储在数组中.你可以使用foreach
:
opendir my($dh), $dirname or die "Could not open directory [$dirname]: $!"; foreach my $file ( sort { $a <=> $b } readdir $dh ) { ... }