Perl 的 opendir 是否应该始终返回 .和..首先?

发布于 2024-08-29 12:10:36 字数 220 浏览 3 评论 0原文

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

看来 99.9% 的情况下,数组中的前两个条目始终是“.”。和 ”..”。如果不正确,脚本中的后续逻辑就会出现问题。我遇到了目录条目稍后出现的情况。这是否表明文件系统已损坏或其他原因? 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

汐鸠 2024-09-05 12:10:36

它始终是操作系统的顺序,未排序的原始顺序。

尽管 。和 .. 通常是前两个条目,这是因为它们是最先创建的两个条目。如果由于某种原因,其中一个被删除(通过非自然序列,因为通常会被阻止),则下一个 fsck (或等效项)将修复目录以再次拥有两者。这会将其中一个名称放在列表中较靠后的位置。

因此,不要只是“跳过前两个条目”。相反,明确匹配它们以拒绝它们。

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.

安人多梦 2024-09-05 12:10:36

该顺序取决于操作系统,并且没有明确定义。

它们很容易被过滤掉。

   opendir MYDIR, "$dir";
   my @FILES = grep !/^\.\.?$/, readdir MYDIR  ;
   closedir MYDIR;

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;
慵挽 2024-09-05 12:10:36

使用 File::Slurp::read_dir 默认情况下,返回一个不包含 ... 的列表。

Use File::Slurp::read_dir which, by default, returns a list that does not include . and ...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文