Perl readdir in order

You can sort by putting folders first and then sorting by file/dir name,

# $src pointing to folder open with opendir
my @sorted_dir = 
  map $_->[0],
  sort {
    $a->[1] <=> $b->[1]
      ||
    $a->[0] cmp $b->[0]
  }
  map [ $_, -f "$src/$_" ],
  readdir($DIR);

While similar effect can be achieved with,

for my $file (sort { -f "$src/$a" <=> -f "$src/$b" } readdir($DIR)) {
  print "$file\n";
}

it's slower and inefficient as it more often goes to file system checking if directory entry is a plain file.


You could use a sort to do it, by looking at each entry of the list returned by readdir.

opendir(my $DIR, '.') or die "Error opening ";

foreach my $file (sort { -d $a <=> -d $b } readdir($DIR)) {
  print "$file\n";
}

This will give folders last.


foreach (sort readdir $dh) {} works fine for me.

For example:

opendir (my $DIR, "$dir") || die "Error while opening $dir: $!\n";

foreach my $dirFileName(sort readdir $DIR)
{
      next if $dirFileName eq '.' or $dirFileName eq '..';
      print("fileName: $dirFileName ... \n");
}