【问题标题】:Dealing with hidden files when making an array of files inside a directory, using Perl使用 Perl 在目录中创建文件数组时处理隐藏文件
【发布时间】:2013-04-19 14:27:04
【问题描述】:

我正在使用 Perl。我正在目录中制作一组文件。以点开头的隐藏文件位于我的数组的开头。我想实际上忽略并跳过这些,因为我不需要它们在数组中。这些不是我要查找的文件。

问题的解决方法似乎很容易。只需使用正则表达式来搜索和排除隐藏文件。这是我的代码:

opendir(DIR, $ARGV[0]);                             
my @files = (readdir(DIR)); 
closedir(DIR);  

print scalar @files."\n"; # used just to help check on how long the array is



for ( my $i = 0; $i < @files; $i++ )
    {
     # ^ as an anchor, \. for literal . and second . for match any following character

     if ( $files[ $i ] =~ m/^\../ || $files[ $i ] eq '.' ) #
        {
         print "$files[ $i ] is a hidden file\n";

         print scalar @files."\n";  
        }

    else
       {
         print $files[ $i ] . "\n";
       }

    } # end of for loop

这会产生一个数组@files 并显示目录中的隐藏文件。下一步是从数组@files 中删除隐藏文件。所以使用shift函数,像这样:

opendir(DIR, $ARGV[0]);                             
my @files = (readdir(DIR)); 
closedir(DIR);  

print scalar @files."\n"; # used to just to help check on how long the array is



for ( my $i = 0; $i < @files; $i++ )
    {
     # ^ as an anchor, \. for literal . and second . for match any following character

     if ( $files[ $i ] =~ m/^\../ || $files[ $i ] eq '.' ) #
        {
         print "$files[ $i ] is a hidden file\n";
         shift @files;
         print scalar @files."\n";  
        }

    else
       {
         print $files[ $i ] . "\n";
       }

    } # end of for loop

我得到了一个意想不到的结果。我的期望是脚本将:

  1. 制作数组@files,
  2. 扫描该数组以查找以点开头的文件,
  3. 找到一个隐藏文件,告诉我找到了,然后及时shift它离开数组的前端@files
  4. 然后向我报告@files的大小或长度,
  5. 否则,只需打印我真正有兴趣使用的文件的名称。

第一个脚本运行良好。脚本的第二个版本,即使用shift 函数从@files 中删除隐藏文件的脚本,确实找到了第一个隐藏文件(. 或当前目录)并将其关闭。它不会向我报告父目录 ..。它也没有找到当前在我的目录中的另一个隐藏文件来测试。该隐藏文件是一个 .DS_store 文件。但另一方面,它确实找到了一个隐藏的 .swp 文件并将其移出。

我无法解释这一点。为什么脚本对当前目录工作正常。但不是父母目录..?另外,为什么脚本对隐藏的 .swp 文件有效,但对隐藏的 .DS_Store 文件无效?

【问题讨论】:

  • 循环中间的 shift @files; 将从数组中删除 $files[0] 并将其他元素向下移动。那么 $files[1] 是新的 $files[0] 等等。 shift ... 不适用于 $files[ $i ],除非 $i==0

标签: arrays perl directory hidden-files


【解决方案1】:

移动文件后,您的索引$i 现在指向以下文件。

您可以使用grep 删除名称以点开头的文件,无需移位:

my @files = grep ! /^\./, readdir DIR;

【讨论】:

  • 如果可以,@choroba,您能否帮我“解开”您的线路。也就是说,我假设您的行是流线型的,因为您可能已经采用了一些更简单的函数并通过更高级的语法将它们合并为一行。我对grep 语法的理解是:grep [which option] 。您是否只是用 readdir 函数替换了最后一个参数?还有,,/readdir之间的作用是什么?
  • grep。它用作过滤器:在逗号之前,有一个否定的正则表达式匹配。 readdir 的每个成员都与之匹配,如果表达式返回 true,则保留在结果中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-15
  • 1970-01-01
  • 2012-03-01
  • 2021-06-07
  • 1970-01-01
  • 1970-01-01
  • 2012-09-25
相关资源
最近更新 更多