为什么readdir()以错误的顺序列出文件名? [英] Why does readdir() list the filenames in wrong order?

查看:153
本文介绍了为什么readdir()以错误的顺序列出文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码从目录中读取文件名并将其推入数组:

I'm using the following code to read filenames from a directory and push them onto an array:

#!/usr/bin/perl

use strict;
use warnings;

my $directory="/var/www/out-original";
my $filterstring=".csv";
my @files;
# Open the folder
opendir(DIR, $directory) or die "couldn't open $directory: $!\n";

foreach my $filename (readdir(DIR)) {
    if ($filename =~ m/$filterstring/) {
        # print $filename;
        # print "\n";
        push (@files, $filename);
    } 
}
closedir DIR;

foreach my $file (@files) {
    print $file . "\n";
}

我从运行此代码得到的输出是:

The output I get from running this code is:

Report_10_2014.csv
Report_04_2014.csv
Report_07_2014.csv
Report_05_2014.csv
Report_02_2014.csv
Report_06_2014.csv
Report_03_2014.csv
Report_01_2014.csv
Report_08_2014.csv
Report.csv
Report_09_2014.csv

为什么这段代码将文件名以此顺序而不是从01推到10的顺序推入数组?

Why is this code pushing the file names into the array in this order, and not from 01 to 10?

推荐答案

Unix目录未按排序顺序存储. Unix命令,例如lssh会为您排序目录列表​​,但是Perl的opendir函数不会;它以与内核存储顺序相同的顺序返回项目.如果要对结果进行排序,则需要自己执行:

Unix directories are not stored in sorted order. Unix commands like ls and sh sort directory listings for you, but Perl's opendir function does not; it returns items in the same order the kernel does, which is based on the order they're stored in. If you want the results to be sorted, you'll need to do that yourself:

for my $filename (sort readdir(DIR)) {

(顺便说一句:裸字文件句柄(如DIR)是全局变量;使用词汇文件句柄(如:

(Btw: bareword file handles, like DIR, are global variables; it's considered good practice to use lexical file handles instead, like:

opendir my $dir, $directory or die "Couldn't open $directory: $!\n";
for my $filename (sort readdir($dir)) {

作为一种安全措施.)

这篇关于为什么readdir()以错误的顺序列出文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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