title: Sorting directory filenames with Perl
body: <p>I want to sort/print the files in a directory by name.  My code lists them all, but the sorting is skewed.  Here is my code and results.  Any suggestions will be most welcomed!</p>
  
  <pre><code>my $file;
  opendir (DIR, "$dir");
  while ($file = readdir(DIR)) {
      push (my @files, $file);
      @files = sort {$a cmp $b} @files;   #NOT sorting!
      foreach $file (@files) {
          print "$file\n";
      }
  }
  </code></pre>
  
  <p>And here are the "sorted" results:  </p>
  
  <pre><code>Screenshot-Chess_-_Human_versus_GNUchess.png  
  test.html  
  katyperry.gif  
  test.cgi  
  Californication.S04E05.HDTV.XviD-ASAP.avi  
  FreeWatch_13.exe  
  proxy.jpg  
  test.pl-  
  .  
  attachment2.jpg  
  attachment.jpg  
  Californication.S04E06.HDTV.XviD-LOL.avi  
  Californication.S04E07.HDTV.XviD-LOL.avi  
  boxter.jpg  
  ..  
  </code></pre>