arrays - 使用 Perl 在目录中创建文件数组时处理隐藏文件

标签 arrays perl directory hidden-files

我正在使用 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. 找到一个隐藏文件,告诉我它找到了一个,然后立即将它到数组的前端 @files,
  4. 然后向我报告@files的大小或长度,
  5. 否则,只打印我真正有兴趣使用的文件的名称。

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

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

最佳答案

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

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

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

关于arrays - 使用 Perl 在目录中创建文件数组时处理隐藏文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16106966/

相关文章:

perl - 如何一个接一个地运行后台进程

perl - 在 perl 中,如何从 STDIN 读取直到我们找到一个空格或换行符?

ruby - 需要 ruby​​ 目录中所有文件的最佳方法?

powershell - Powershell 中的 `mkdir -p` 是什么?

php - 如何用键和值分解多维数组

c - char数组前面的&符号会影响scanf吗?合法吗?

perl - 推荐一个 WYSIWYG GUI creator for Perl

php - 在我的 index.php 中加载 CSS 和 JS 等资源时出现错误 403

C程序删除字符串中所有不必要的空格

ios - 如何将数组插入Sqlite数据库