我正在使用將目錄名稱作爲用戶輸入並在其中搜索文件的perl腳本。搜索文件後,它讀取文件的內容。如果文件內容包含一個單詞「板球」,然後使用取消鏈接功能,我應該能夠刪除該文件。但是使用unlink
之後,包含單詞「cricket」的文件在執行代碼後仍然存在於目錄中。請幫忙。我的代碼是:perl無法使用Unlink刪除文件
use strict;
use warnings;
use File::Basename;
print "enter a directory name\n";
my $dir = <>;
print "you have entered $dir \n";
chomp($dir);
opendir DIR, $dir or die "cannot open directory $!";
while (my $file = readdir(DIR)) {
next if ($file =~ m/^\./);
my $filepath = "${dir}${file}";
print "$filepath\n";
print " $file \n";
open(my $fh, '<', $filepath) or die "unable to open the $file $!";
my $count = 0;
while (my $row = <$fh>) {
chomp $row;
if ($row =~ /cricket/) {
$count++;
}
}
print "$count";
if ($count == 0) {
chomp($filepath);
unlink $filepath;
print " $filepath deleted";
}
}
您是否有權寫入該文件? – McKracken 2014-11-09 07:29:47
看起來你正試圖「解開」一個打開的文件。 – 2014-11-09 07:30:45