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

84a*_*dam 12 perl shebang use-strict

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

use strict;
use warnings;
Run Code Online (Sandbox Code Playgroud)

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

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

print "Hello, World!\n";
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,我得到的回报是"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.
Run Code Online (Sandbox Code Playgroud)

我创建了其它的"Hello World"程序.随后,而不包含use strict;use warnings;线条,并且还一个用-w,我在一些教程已经看到,这表明,如果我没有记错的话,这将警告被打开.

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

Hello, World!
Run Code Online (Sandbox Code Playgroud)

我不能确定的是,我是否需要use从版本5.14及更高版本的Perl程序中的语句,或者如果-w在第一行的末尾写入它就好了.

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

dgw*_*dgw 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" ;
Run Code Online (Sandbox Code Playgroud)

打电话perl script1.pl

Hello world.
Run Code Online (Sandbox Code Playgroud)

script2.pl

!#/usr/bin/perl

use strict;
use warnings ;

print "Hello world.\n" ;
Run Code Online (Sandbox Code Playgroud)

打电话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.
Run Code Online (Sandbox Code Playgroud)

使用正确的语法script3.pl

#!/usr/bin/perl

use strict ;
use warnings ;

print "Hello world.\n" ;
Run Code Online (Sandbox Code Playgroud)

打电话perl script3.pl

Hello world.
Run Code Online (Sandbox Code Playgroud)

  • 你的*script1.pl*不会忽略错误的shebang行,因为很明显当你写`!#`时它不是一个shebang行.它是`!`(非)运算符,后跟注释.所以它与编写`!print`是一样的:反转`print`语句的返回值 - 当然,无论如何都会被忽略.在*script2.pl*中它正在执行`!use`,这没有意义,因为`use`是一个编译时构造,而不是运行时函数. (3认同)

ike*_*ami 9

你做了类似的事情

use warnings
use strict;
Run Code Online (Sandbox Code Playgroud)

代替

use warnings;
use strict;
Run Code Online (Sandbox Code Playgroud)

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


如其他地方所述,您发布的代码和您使用的代码是不同的.你真的用过

!use strict;
Run Code Online (Sandbox Code Playgroud)

由于一个糟糕的shebang线.

!#/u...         # Negation followed by a comment
Run Code Online (Sandbox Code Playgroud)

应该

#!/u...         # Shebang
Run Code Online (Sandbox Code Playgroud)