perl - 如何在 Perl 中读取空文件

标签 perl

我正在使用 readdir 方法将文件列表从目录读取到数组。我可以知道如何读取零大小文件,因为 readdir 只会读取非零大小文件。我也想读取空文件(捕获文件名作为存在,即使它是空的)。我可以知道该怎么做吗?以下是我从目录中读取文件的方法:-

opendir (FH, $dirs) || die $! ;
my @lines = readdir (FH) ; 
closedir (FH) ;

提前谢谢您。

最佳答案

首先,您不应该使用裸字目录句柄。二、-z tells you when a file is empty 。像这样的东西应该有效:

use strict;
use warnings;

my $dirs="/whatever/dir/you/want";

opendir(my $dh,$dirs) or die $!;

#only grabbing actual files that we can read.
my @files=grep{(-f $_) and (-r $_)} map{"$dirs/$_"} readdir($dh); 

closedir($dh);

foreach my $file(@files)
{
  if(-z $file)
  {
    print "File $file is empty.\n";
  }
  else
  {
    print "File $file is not empty.\n";
  }
}

事实上,正如 TLP 在注释中指出的那样,您可以使用 -s 来获取文件的大小(以字节为单位)。

关于perl - 如何在 Perl 中读取空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9205341/

相关文章:

perl - Perl 中将迭代器扩展为列表的最优雅的方式是什么?

perl - 无法编译我的 perl 脚本。让一切正常工作的最简单方法是什么?

perl - 遍历数组后返回 bool 值

perl - 寻找以 DDMMYY 格式生成昨天日期的 Perl 5.12 代码

perl - perl 的 autodie.pm 中的错误?

perl - 设置 cygwin 终端窗口的大小

python - Python 中的 ID3 标签 - Python 是执行此任务的错误语言吗?

perl - 为自记录代码初始化 "undef"?

linux - 如何防止 Perl 脚本并行运行多次

perl - 如何获取列表以显示 Perl 中空条目的零?