您如何检查Perl中打开(文件)是否成功? [英] How do you check the success of open (file) in Perl?
问题描述
以下(不是很Perl的)代码
The following (not very Perl-ish) code
#!/usr/bin/perl
if (! -e "mydir/")
{
print "directory doesn't exist.\n";
}
open (my $fh, ">", "mydir/file.txt");
if ($fh)
{
print "file opened.\n";
print $fh;
print $fh "some text\n" or die "failed to write to file.\n";
close ($fh);
}
else
{
print "failed to open file.\n";
}
产生这样的输出
directory doesn't exist.
file opened.
failed to write to file.
GLOB(0x...some-hex-digits...)
为什么在公开通话后 $ fh 不等同于false?由于 mydir/不存在,我希望打开文件的尝试失败.
Why is $fh not equivalent to false following the open call? As mydir/ does not exist, I'd expect the attempt to open the file to fail.
如果目录和文件存在,但文件是只读的,我得到类似的结果.
I get similar results if the directory and file exist, but the file is read-only.
我已经在Windows 7 x64的Perl 5.10.1和Fedora-11 Linux的Perl 5.10.0上进行了尝试.
I've tried this with Perl 5.10.1 on Windows 7 x64, and with Perl 5.10.0 on Fedora-11 Linux.
我猜我的文件句柄测试是错误的.我尝试了Google搜索,但是没有运气.我希望这很明显,但是任何提示或链接都将不胜感激.
I'm guessing my file handle test is wrong. I've tried Googling this without luck. I expect it's something obvious, but any hints or links would be much appreciated.
谢谢,罗布.
推荐答案
$ fh
未被设置为零位值,而是被设置为 GLOB 代码>,如代码所示.这与
open
返回的内容不同,这就是习惯用法所在的原因
$fh
isn't being set to a zero-ish value, it is being set to a GLOB
as your code shows. This is different from what open
returns which is why the idiom is
open(...) or die ... ;
或
unless(open(...)) {
...
}
这篇关于您如何检查Perl中打开(文件)是否成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!