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

时间:2016-02-24 20:00:58

标签: 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;

1 个答案:

答案 0 :(得分:8)

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

open(my $fh, '>', $filename) or die("Couldn't open $filename\n");

您可以使用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 "::").