Perl的’readdir’功能结果顺序?

前端之家收集整理的这篇文章主要介绍了Perl的’readdir’功能结果顺序?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在 Windows中运行Perl,我使用readdir获取目录中所有文件的列表,并将结果存储在数组中.数组中的前两个元素似乎总是“.”和“……”.这个订单是否有保证(假设操作系统没有改变)?

我想执行以下操作来删除这些值:

my $directory = 'C:\\foo\\bar';

opendir my $directory_handle,$directory 
    or die "Could not open '$directory' for reading: $!\n";

my @files = readdir $directory_handle;
splice ( @files,2 ); # Remove the "." and ".." elements from the array

但我担心这样做可能不安全.我见过的所有解决方案都使用了数组中每个元素的正则表达式或if语句,如果我不需要,我宁愿不使用这些方法.思考?

解决方法

readdir的顺序无法保证. The docs state它……

Returns the next directory entry for a directory opened by opendir.

整个过程是按文件系统提供的顺序逐步浏览目录中的条目.无法保证此订单可能是什么.

解决这个问题的常用方法是使用正则表达式或字符串相等.

my @dirs = grep { !/^\.{1,2}\z/ } readdir $dh;

my @dirs = grep { $_ ne '.' && $_ ne '..' } readdir $dh;

因为这是一个常见的问题,我建议使用Path::Tiny->children而不是自己滚动.他们已经找到了最快最安全的方法,即使用grep过滤掉.和… Path :: Tiny修复了很多关于Perl文件和目录处理的东西.

猜你在找的Perl相关文章