perl - 如何在两行中检查文件是否已成功打开

标签 perl

抱歉,我找不到这个问题的答案。

如果我有以下行

my $FH;
open FH,"somefile";

现在我想检查 FH 是否已成功打开,但我想在不同的行中执行此操作,而不是使用 or 语法。

我尝试了 if ( $FH ),但它对我不起作用。

谢谢。

最佳答案

来自open-Manual :

Open returns nonzero on success, the undefined value otherwise. If the open involved a pipe, the return value happens to be the pid of the subprocess.

所以你可以这样做:

my $FH;
my $file_opened = open $FH, '<', 'somefile';

if($file_opened) {
    print "open";
    close($FH);
}

或者一行中没有附加变量:

if(open $FH, '<', 'somefile') {
    print "--open";
    close($FH);
}

关于perl - 如何在两行中检查文件是否已成功打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7662090/

相关文章:

perl - 用 perl 错误编写 utf8?

Perl 长数据类型

perl - 如何使用 Perl 模块 HTTP::Async 处理超时?

linux - 如何让 Log4perl 每天轮换我的日志?

regex - 在替换中操作正则表达式匹配

string - 从 perl 中的字符串中删除多个新行

perl - 如何在 nginx 错误日志中获取 perl 脚本错误(Nginx with FCGIwrap)

php - mysql 或 perl 函数匹配 Asterisk 拨号方案模式

linux - 在 Perl 中从管道读取无缓冲数据

perl - CHECK 和 INIT block 怎么了?