2016-05-12 47 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

相關問題