Perl:opendir,而readdir,next if,hash [英] Perl: opendir, while readdir, next if, hash
问题描述
我有一个名为 $ tmp
的目录,其中包含名称语法 .X * -lock
的文件,以及其他纯文件和目录。
I have a directory $tmp
that contains files with the name syntax .X*-lock
as well as other plain files and directories.
我将 $ tmp
的内容与散列表中的值对应于进行比较。 X * -lock
不应删除的文件名。然后,我希望脚本删除任何不在散列表中的 .X * -lock
文件。它不能删除纯文件(非。文件),目录或。
& ..
I compare the contents of $tmp
with values in a hash table corresponding to .X*-lock
file names that should NOT be deleted. I then want the script to delete any, and ONLY .X*-lock
files that aren't in the hash table. It cannot delete plain files (non "." files), directories, or .
& ..
以下是一些代码:
here's some code:
my %h = map { $_ => 1 } @locked_ports;
#open /tmp and find the .X*-lock files that DO NOT match locked_ports (NOT WORKING)
opendir (DIR, $tmp ) or die "Error in opening dir $tmp\n";
while ( (my $files = readdir(DIR)))
{
next if((-f $files) and (-d $files));
next if exists $h{$files};
#unlink($files) if !-d $files;
if (! -d $files){print "$files\n"};
}
closedir(DIR);
正如您所看到的,现在我将取消链接
with print >所以我知道列出了正确的文件。
As you can see, for now I replaced unlink
with print
so I know the proper files are being listed.
在我的 $ tmp
dir我有以下文件和目录:
Let's say in my $tmp
dir I have the following files and directories:
./
../
cheese
.X0-lock
.X10-lock
.X11-unix/
.X1-lock
.X2-lock
.X3-lock
.X4-lock
.X5-lock
<但只有 .X1-lock
位于散列表中。因此,我想打印/删除所有其他 .X * -lock
文件,但不是 .X11-unix /
dir, cheese
文件或。
& ..
But only .X1-lock
is in the hash table. Thus I want to print/delete all other .X*-lock
files, but not the .X11-unix/
dir, the cheese
file, or the .
& ..
使用上面的代码,它不会打印。
或 ..
这是好的,但它会打印 cheese
和 .X11 -unix
。我怎样才能改变它,所以这些都不会被打印?
With the above code, it does not print .
or ..
which is good, but it does print cheese
and .X11-unix
. How can I change it so these are not printed as well?
(注意:这是一个干掉 Perl:foreach line,split,修改字符串,设置为数组。如果files = modified string。Unlink files 我被告知不要再在评论中提出更多问题,所以我提出了一个新问题。)
(note: this is a stem off Perl: foreach line, split, modify the string, set to array. Opendir, next if files=modified string. Unlink files I was told to stop asking more questions in the comments so I made a new question.)
谢谢!我可能会这样做:
Thanks!
解决方案
推荐答案
opendir(my $ dirhandle,$ tmp)或死于打开目录$ tmp:$!时出错;
while(my $ file = readdir($ dirhandle)){
#跳过哈希中的目录和文件
next if -d$ tmp / $ file|| $ H $ {}文件;
#跳过看起来不像.X的文件### - 锁定
next,除非$ file =〜/
\##字符串
\开头。 #'文字'。'
X#文字'X'
\ d +#1或更多数字
-lock#文字串'-lock'
\ z #字符串的结尾
/ x; #'x'允许在正则表达式中使用空格和注释
#unlink($ tmp / $ file);
print$ file\\\
}
closedir($ dirhandle);
如果您发现它更具可读性,那么最后的条件可以写为:
If you find it more readable, that last conditional could be written as:
next if $file !~ /\A\.X\d+-lock\z/;
甚至:
or even:
if ($file =~ /\A\.X\d+-lock\z/) {
# unlink("$tmp/$file");
print "$file\n"
}
这篇关于Perl:opendir,而readdir,next if,hash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!