perl - Why does readdir() list the filenames in wrong order? -
i'm using following code read filenames directory , push them onto array:
#!/usr/bin/perl use strict; use warnings; $directory="/var/www/out-original"; $filterstring=".csv"; @files; # open folder opendir(dir, $directory) or die "couldn't open $directory: $!\n"; foreach $filename (readdir(dir)) { if ($filename =~ m/$filterstring/) { # print $filename; # print "\n"; push (@files, $filename); } } closedir dir; foreach $file (@files) { print $file . "\n"; }
the output running 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
why code pushing file names array in order, , not 01
10
?
unix directories not stored in sorted order. unix commands ls
, sh
sort directory listings you, perl's opendir
function not; returns items in same order kernel does, based on order they're stored in. if want results sorted, you'll need yourself:
for $filename (sort readdir(dir)) {
(btw: bareword file handles, dir
, global variables; it's considered practice use lexical file handles instead, like:
opendir $dir, $directory or die "couldn't open $directory: $!\n"; $filename (sort readdir($dir)) {
as safety measure.)
Comments
Post a Comment