ES5*_*S55 2 arrays directory perl 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
Run Code Online (Sandbox Code Playgroud)
这会生成一个数组,@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
Run Code Online (Sandbox Code Playgroud)
我得到了意想不到的结果.我的期望是脚本将:
@files,shift它从阵列的前端移开@files,@files,第一个脚本工作正常.脚本的第二个版本,即使用该shift功能从中删除隐藏文件的脚本,@files确实找到了第一个隐藏文件(.或当前目录)并将其移除.它没有向我报告父目录.. 它也找不到我目录中的另一个隐藏文件来测试.该隐藏文件是.DS_store文件.但另一方面,它确实找到了一个隐藏的.swp文件并将其移出.
我无法解释这一点.为什么脚本对当前目录运行正常.但不是父母目录..?而且,为什么脚本对于隐藏的.swp文件而不是隐藏的.DS_Store文件可以正常工作?
移动文件后,您的索引$i现在指向以下文件.
你可以grep用来摆脱名字以点开头的文件,不需要转移:
my @files = grep ! /^\./, readdir DIR;
Run Code Online (Sandbox Code Playgroud)