如何通过遍历文件名数组来检查文件内容是否为空

How to check whether file content is empty , by traversing the array of filenames

我有一个文件名数组,我必须遍历这个数组并检查所有文件的内容是否为空。

这是代码

foreach my $reportFile (sort { getDateInName($b) <=> getDateInName($a)} @ReportFiles)
{
   my @fileData = readFile($reportFile);
   if(!@fileData)
   {
        outputLog("FAIL: File Doesnt Contain Any Data.");
        return;
   }
}

但在上面的代码中,即使单个文件为空,我也会 returning, 我想知道我们如何检查所有文件的所有内容是否为空然后 return.

所以我想 return 仅当数组中的 none 个文件有内容时。

即使一个文件有内容我也不会return

谢谢

首先,如果您只想检查文件是否为空,则不应尝试读取它。这可能很危险,因为您可能最终会在内存中读取一个巨大的文件。您可以像那样测试文件是否为空 if (-s $reportFile) {...}。其次,要解决任何文件为空时返回的问题,您需要反转代码的逻辑,即您必须检查是否有任何文件 not 为空。这是因为以下逻辑等价:说 "all the files are empty" 与 "no file is nonempty" 相同。把它们放在一起,你会得到这样的东西:

sub all_empty {
    foreach my $reportFile (sort { getDateInFileName($b) <=> getDateInName($a)} @ReportFiles)
    {
       if (-s $reportFile) {
           return 0;
       }
    }
    return 1;
}

尝试有一个布尔标志,如果您至少有一个文件中有内容,则将其设置为 1,这样您就不必遍历数组并且 return 一旦找到文件有内容 如果文件中没有内容,则转到下一次迭代以检查内容是否可用。 如果任何文件中存在内容,则跳出循环

my $isFileEmpty = 0 ;
foreach my $reportFile (sort { getDateInFileName($b) <=> getDateInName($a)} @ReportFiles)
{
    my @fileData = readFile($reportFile);
   if(@fileData) {
      $isFileEmpty = 1;
      last;     
   }
   else {
      next ; 
    } 
}
if($isFileEmpty eq 0)
{

    return;

}


PS : Do you have content available in most of the cases ?

使用List::Util::all:

Similar to any, except that it requires all elements of the @list to make the BLOCK return true. If any element returns false, then it returns false. If the BLOCK never returns false or the @list was empty then it returns true.


use List::Util 'all';

sub check_files {
  ...
  warn( "All files empty" ), return
    if all { -z } @_;
  ...
}

sub are_all_empty { all { -z } @_ }