在Perl中使用列表上下文中的菱形运算符时,为什么会出现关闭的文件句柄错误?

gvk*_*vkv 4 perl diamond-operator

这段代码:

foreach my $file (@data_files) {

    open my $fh, '<', $file || croak "Could not open file $file!\n";
    my @records = <$fh>;
    close $fh;

    ....

}
Run Code Online (Sandbox Code Playgroud)

产生此错误:

readline() on closed filehandle $fh at nut_init_insert.pl line 29.
Run Code Online (Sandbox Code Playgroud)

而且我不知道为什么.

编辑:原始帖子在open声明中有','而不是'<' .

FMc*_*FMc 11

您发布的代码中有一个拼写错误(第二个参数open),但这并不能解释错误消息.该问题的信息是这样的:

Unknown open() mode ',' at ...
Run Code Online (Sandbox Code Playgroud)

您的问题与优先级有关.在||结合得太紧,导致Perl来对待这整个表达式作为第三个参数打开:

$file || croak $!
Run Code Online (Sandbox Code Playgroud)

结果,即使open失败(可能因为$file不是有效的文件名),croak也不执行(因为$file是真的和||短路).在后open失败,你的程序尝试读取一个未开封的文件句柄的某些行,你会得到这样的错误信息:

readline() on closed filehandle $fh at ...
Run Code Online (Sandbox Code Playgroud)

您想要使用以下之一.第二个选项有效(与您的代码不同),因为or优先级较低.

open(my $fh, '<', $file) || croak ...;

open my $fh, '<', $file or croak ...;
Run Code Online (Sandbox Code Playgroud)

有关运算符优先级的详细信息,请参阅perlop.您的案例中的相关点是||运算符的优先级高于列表分隔符(逗号).