Perl检查文件是否打开
我正在使用perl 5.005_30版本 在执行任何操作之前,我需要检查“.doc”文件是否已在使用中 我已经编写了以下代码Perl检查文件是否打开,perl,Perl,我正在使用perl 5.005_30版本 在执行任何操作之前,我需要检查“.doc”文件是否已在使用中 我已经编写了以下代码 my $doc = "D:\Test.doc"; eval{open FILE, ">$doc" or die "error"}; if($@) { my $ERR_MSG ="Could not open the file \"$doc\" !\n Please close the file if it is already open and try a
my $doc = "D:\Test.doc";
eval{open FILE, ">$doc" or die "error"};
if($@)
{
my $ERR_MSG ="Could not open the file \"$doc\" !\n Please close the file if it is already open and try again !!\n";
open (LOGFILE, '>>Logfile.txt');
print LOGFILE "$ERR_MSG\n";
}
else
{
close(FILE); // close the opened file and start operations on ".doc" file using MS word API.
...
...
}
使用此代码,如果“Test.doc”已经打开,它会在日志文件中打印一条错误消息,这是正常的。但是,如果“Test.doc”尚未打开,则打开方法将打开.doc文件,并在关闭文件[“close(file)”]时在else条件下删除“Test.doc”的现有内容,文档将变为空
请告诉我如何关闭文件而不清空其内容。这将覆盖它:
eval{open FILE, ">$doc" or die "error"};
您可以尝试打开它进行追加:
eval{open FILE, ">>$doc" or die "error"};
不要使用上个世纪的perl版本。升级到最新版本。5.18.2现在已稳定。请使用“独占”以确保文件未被使用。这可能不是最好的方法,但您可以尝试打开文档以附加
>
,而不是使用
进行重击。此外,您可以只检查open
的返回值,而不必使用eval
。这实际上不符合答案的条件。抱歉,您发表此评论时我正在键入我的答案。虽然我猜API希望无论如何都能打开文件本身,但我不确定整个练习是否有意义。