为什么不允许“使用”,如“严格使用”;在Perl 5.14?

时间:2013-01-13 07:13:50

标签: perl shebang use-strict

我正在尝试使用以下约定,我已被指示用于"Hello, World!"程序的良好/正确/安全的Perl代码:

use strict;
use warnings;

我已经在我的主Windows 7操作系统上使用(Strawberry)Perl 5.12创建并成功运行了以下“Hello World”程序:

!#/usr/bin/perl
use strict;
use warnings;

print "Hello, World!\n";

我按预期得到的是"Hello, World!"

让我感到非常奇怪的是,使用Perl 5.14在我的虚拟化Linux Mint 14操作系统上运行终端的同一程序产生了以下错误:

"use" not allowed in expression at /PATH/hello_world.pl line 2, at end of line
syntax error at /PATH/hello_world.pl line 2, near "use strict"
BEGIN not safe after errors--compilation aborted at /PATH/hello_world.pl line 3.

我随后创建了其他“Hello World”程序,没有use strict;use warnings;行,还有一个-w,我在一些教程中看到过,表明,如果我没有记错,警告会被打开。

我的两个备用版本都正常工作,因为它们产生了我预期的结果:

Hello, World!

我无法确定的是,如果我需要从版本5.14开始的Perl程序中的use语句,或者在第一行末尾写-w就好了。

我想我可以在我的所有Perl程序中使用一致的标头,无论它们是Windows还是Linux,Perl 5.12或5.14还是其他。

2 个答案:

答案 0 :(得分:16)

您的图片显示所有脚本都以!#/usr/bin/perl开头。这是错的。它不是一个有效的she-bang系列,它被视为否定!后跟评论#。解析将继续, script1.pl perl将执行! print "Hello world.\n";。这将打印Hello world并否定print的结果...不是真的有用,但是有效的perl。

script2.pl 中,perl看到! use strict;这是一个编译时错误,因此perl失败并报告行use strict;的错误。

因此,如果您使用正确的she-bang行,则所有三个脚本都将按设计工作。

编辑(添加测试脚本):

<强> script1.pl

!#/usr/bin/perl

print "Hello world.\n" ;

致电perl script1.pl给出

Hello world.

<强> script2.pl

!#/usr/bin/perl

use strict;
use warnings ;

print "Hello world.\n" ;

致电perl script2.pl给出

"use" not allowed in expression at script2.pl line 3, at end of line
syntax error at script2.pl line 3, near "use strict "
BEGIN not safe after errors--compilation aborted at script2.pl line 4.

使用正确的语法 script3.pl

#!/usr/bin/perl

use strict ;
use warnings ;

print "Hello world.\n" ;

致电perl script3.pl给出

Hello world.

答案 1 :(得分:9)

你做了类似

的事情
use warnings
use strict;

而不是

use warnings;
use strict;

实际上,我认为这可能是一个终结问题。你有LF你应该有CR LF,反之亦然。我已经看到这导致Perl认为代码在shebang行中途开始(例如perl use strict;


如其他地方所述,您发布的代码和您使用的代码是不同的。你实际上用过

!use strict;

由于shebang线不好。

!#/u...         # Negation followed by a comment

应该是

#!/u...         # Shebang