理解perl feature指令
2013-03-18 17:59:01 阿炯

Perl 在5.8(不包括)以后,从5.10正式版开始,引入了'feature'指令,用于在其新版本里开启哪些新特性。这些特性是在以前版本直接没有的,表现在更加简单的操作,使之更加人性化。

feature - Perl pragma to enable new features

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.

有三种使用'feature'指令的方法:

1)、在'use'时声明要导入的方法
use feature qw(switch say);

注意:所用的Perl版本里必须要有这些方法,不然会出错。

2)、在'use'时直接声明要使用的版本
use feature ":5.10";

这样就导入了该版本里所支持的所有指令。后面的版本包括了前面版本所包含的方法,到目前各生产版本的包含情况如下:
bundle    features included
--------- -----------------
:default  array_base

:5.10     say state switch array_base

:5.12     say state switch unicode_strings array_base

:5.14     say state switch unicode_strings array_base

:5.16     say state switch unicode_strings unicode_eval evalbytes current_sub fc

The :default bundle represents the feature set that is enabled before any use feature or no feature declaration.

3)、use 对应在版本
use v5.10.0;
即相当于:
no feature ':all';
use feature ':5.10';

这可能会造成代码在平台间移植有问题,所以推荐使用:
use 5.010;

If the required version is older than Perl 5.10, the ":default" feature bundle is automatically loaded instead.
当正在使用的版本低于当前的'5.10'时,将会自动使用'use feature ":default";'来代替。从5.10开始,新特性必须开启才能使用,Perl默认不启用新特性保持向后兼容。

如果想启用新特性,可以使用新的-E开关,来打开所有的新特性。
$ perl5.10.1 -E say.pl #开启5.10.1 版本的所有新特性

在源代码中使用 use 指令之后指定perl版本号就可以了。

use 5.010; # 打开5.10版以来的新特性

从5.12 之后直接指定版本号,自动打开约束指令。

如果不希望打开所有的新特性,可以使用feature编译指令,仅打开需要的特性。
use feature qw(switch say)

参考来源:http://perldoc.perl.org/feature.html