coolboarderguy has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,

playing with this basic script,

#!/usr/bin/perl use strict; use warnings; use File::Find; my $dir = shift; find(\&print_name_if_file, "$dir"); sub print_name_if_file { print "$_\n" if -f; }

and was wondering why the files are printed out of order? I know of the sort utility, but, why doesn't it print the same order as a normal ls -al does? Cheers.

Perl output

[racket@ibmlap perl]$ ./filechng.pl testdir file4.pdf file5.pdf file2.pdf file3.pdf file10.pdf file7.pdf file9.pdf file8.pdf file1.pdf file6.pdf

Here is the ls -al output

[racket@ibmlap perl]$ ls -al testdir total 56 drwxrwxr-x 2 racket racket 4096 Mar 24 14:59 . drwxrwxr-x 3 racket racket 4096 Mar 24 15:08 .. -rw-rw-r-- 1 racket racket 0 Mar 24 14:59 file10.pdf -rw-rw-r-- 1 racket racket 0 Mar 24 14:58 file1.pdf -rw-rw-r-- 1 racket racket 0 Mar 24 14:58 file2.pdf -rw-rw-r-- 1 racket racket 0 Mar 24 14:58 file3.pdf -rw-rw-r-- 1 racket racket 0 Mar 24 14:58 file4.pdf -rw-rw-r-- 1 racket racket 0 Mar 24 14:59 file5.pdf -rw-rw-r-- 1 racket racket 0 Mar 24 14:59 file6.pdf -rw-rw-r-- 1 racket racket 0 Mar 24 14:59 file7.pdf -rw-rw-r-- 1 racket racket 0 Mar 24 14:59 file8.pdf -rw-rw-r-- 1 racket racket 0 Mar 24 14:59 file9.pdf

Cheers.

coolboarderguy...

Replies are listed 'Best First'.
Re: Files Print Out Of Order
by superfrink (Curate) on Mar 24, 2006 at 06:29 UTC
    In short the "ls" program actually sorts the files before displaying the list. There are other sorting options for "ls". I often use "ls -lrt | tail" for example.

    Rather than explain it here I'm just going to point you to Order of files returned by readdir.
      Hi All,

      yes, no need for you to do the work for me. Cheers.

      coolboarderguy...