Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Perl's opendir always return . and .. first?

Tags:

perl

opendir

  opendir MYDIR, "$dir";
  my @FILES = readdir MYDIR;
  closedir MYDIR;

It appears that 99.9 % of the time the first two entries in the array are always “.” and “..”. Later logic in the script has issues if it is not true. I ran into a case where the directory entries appeared later. Is this indicative of the file system being corrupt or something else? Is there a known order to what opendir returns?

like image 257
ojblass Avatar asked Apr 16 '10 15:04

ojblass


2 Answers

It's always the operating-system order, presented unsorted raw.

While . and .. are very often the first two entries, that's because they were the first two entries created. If for some reason, one of them were deleted (via unnatural sequences, since it's normally prevented), the next fsck (or equivalent) would fix the directory to have both again. This would place one of the names at a later place in the list.

Hence, do not just "skip the first two entries". Instead, match them explicitly to reject them.

like image 192
Randal Schwartz Avatar answered Sep 22 '22 15:09

Randal Schwartz


The order is down to the OS and is explicitly not otherwise defined.

They're easy enough to filter out.

   opendir MYDIR, "$dir";
   my @FILES = grep !/^\.\.?$/, readdir MYDIR  ;
   closedir MYDIR;
like image 29
Penfold Avatar answered Sep 24 '22 15:09

Penfold