2016-05-12 70 views
13

这个问题可能很愚蠢。但我刚开始探索Perl。我正在使用Perl v5.16.2。我知道在5.10中已经引入了say声明。为什么我应该在使用say函数时指定使用语句?

#!/usr/bin/perl 

say "Hello World!"; 

当我尝试上述程序运行,我收到以下错误:

$ ./helloPerl 
String found where operator expected at ./helloPerl line 3, near "say "Hello World!"" 
    (Do you need to predeclare say?) 
syntax error at ./helloPerl line 3, near "say "Hello World!"" 
Execution of ./helloPerl aborted due to compilation errors. 

但是,当我加入的声明use 5.016;,它给我正确的输出。

#!/usr/bin/perl 

use 5.016; 
say "Hello World!"; 

我的疑问是,我使用的是perl v5.16.2,它是5.010以上。为什么要在这里使用use声明提到Perl版本?

回答

17

可能会破坏向后兼容性的功能默认情况下未启用。

perldoc feature

It is usually impossible to add new syntax to Perl without breaking some existing programs. This pragma provides a way to minimize that risk. New syntactic constructs, or new semantic meanings to older constructs, can be enabled by use feature 'foo' , and will be parsed only when the appropriate feature pragma is in scope. (Nevertheless, the CORE:: prefix provides access to all Perl keywords, regardless of this pragma.)

use上一个版本号,隐含启用所有功能,因为它也适用于Perl版本的约束。因此,例如,您不会因为未实施say而绊倒。

+1

我想指出的是,这在以前是语法错误,一些功能可能不需要'use'语句启用。 –

+1

我认为你的意思是's/pattern/newpattern/r'和'$ var // 0'类型的东西?对,那是正确的。他们不打算向后兼容。你仍然可以通过'use'强制执行一个最低版本的perl版本(如果你正在做一些依赖于版本的版本,可能应该这样做) – Sobrique

14

say是一个功能,它不是(它会永远不会?)常规Perl语法。

二者必选其一

use feature qw(say); 

use v5.010; # or any version later 
+5

我认为它不会是,因为它是向后兼容性和设计问题。从历史上看,perl并没有使以前的'好'代码失效,这就是为什么例如“strict”和“warnings”是可选的,尽管它是一个非常好的主意。 – Sobrique

相关问题