为什么'使用严格'不允许我写入文件?

anu*_*amb 1 perl

嗨,我是Perl世界的新人.为什么'use strict'不允许我打开并写入文件,如下面的代码?评论'use strict'非常有效.

use strict;
use warnings;

my $filename = "file_abc.txt";
open($fh, '>', $filename) or die("Couldn't open $filename\n");
print $fh "ABC";
print $fh "DEF\n";
print $fh "GHI";
close $fh;
Run Code Online (Sandbox Code Playgroud)

too*_*lic 8

使用时strict,您需要使用以下内容声明每个变量my:

open(my $fh, '>', $filename) or die("Couldn't open $filename\n");
Run Code Online (Sandbox Code Playgroud)

您可以获取有关通过使用一些错误消息的详细信息use diagnostics;:

Global symbol "$fh" requires explicit package name at ...
Execution of ... aborted due to compilation errors (#1)
    (F) You've said "use strict" or "use strict vars", which indicates 
    that all variables must either be lexically scoped (using "my" or "state"), 
    declared beforehand using "our", or explicitly qualified to say 
    which package the global variable is in (using "::").
Run Code Online (Sandbox Code Playgroud)

  • 您不必使用`my`声明每个变量.您必须声明它们或使用其包前缀变量名称. (2认同)