I have written a Perl script which opens a directory consisting of various files. It seems that the script does not read the files in any sequential order (neither alphabetically nor size wise) instead it reads them randomly. I was wondering what could be the reason behind the same?
views:
656answers:
4It's probably reading them according to the order they're stored in the directory's list of files. On certain Unix-like filesystems, the directory is essentially an unordered list of filenames and inodes that point to the contents (this is tremendously simplified).
If your script uses opendir() (directly or indirectly), you cannot assume anything about the ordering ordering of the files it returns; it will depend on the OS and type of filesystem you are accessing. A couple of options are:
1) use two loops: one to read all the filenames, the second to process them in the order you require.
2) use some other command (like invoking "ls") to force the filenames to be returned in the order you require.
It's never random, it's just in a pattern that you don't recognize. If you look at the documentation that describes the implementation of whatever function you're using to read the directory, it would probably say something like, does not guarantee the order of the files to be read.
If you need them in a specific order, sort the names before you operate on them.
The files are probably read in an order that's convenient for the underlying file system. So, in a sense, the files are ordered, but not in an order you expect (size or alphabetical). Sometimes, files have an internal numerical id, and the files may be returned in numerical order given this id. But this id is something you probably won't encounter often if ever.
Again, the results are ordered, not random. They're just in an order that you're not expecting. If you need them ordered, order them explicitly.
See also: http://www.perlmonks.org/?node_id=175864
Directory entries are not stored in sorted order and you should not assume they're stored that way. If you want to sort them, you have to sort them. For example, compare the output of:
perl -e 'opendir DIR, "."; print join("\n", sort readdir(DIR)); print "\n";'
perl -e 'opendir DIR, "."; print join("\n", readdir(DIR)); print "\n";'