我正在使用Safe模块以包含在Mastering Perl中。v5.16 之前的版本(支持的最早版本)似乎不理解新关键字。我错过了什么吗?
说适用于 v5.16 及更高版本
use v5.10;
use Safe;
say "Running $0 under $^V with Safe ", Safe->VERSION;
my $compartment = Safe->new;
$compartment->permit( ':base_io', ':load' );
my $code =<<"CODE";
use v5.10;
say "Hello Safe!";
CODE
$compartment->reval( $code ) or do {
my $error = $@;
warn "Safe compartment error! $@";
};
这段代码在 v5.18 和 v5.16 下运行,这两个Perl 官方支持的版本:
% perl5.18.0 safe.pl
Running safe.pl under v5.18.0 with Safe 2.35
Hello Safe!
% perl5.16.3 safe.pl
Running safe.pl under v5.16.3 with Safe 2.35
Hello Safe!
它在 v5.16 之前不起作用,因为它认为say关键字无效:
% perl5.14.4 safe.pl
Running safe.pl under v5.14.4 with Safe 2.35
String found where operator expected at (eval 5) line 2, near "say "Hello Safe!""
(Do you need to predeclare say?)
Safe compartment error! syntax error at (eval 5) line 2, near "say "Hello Safe!""
% perl5.12.3 safe.pl
Running safe.pl under v5.12.3 with Safe 2.35
String found where operator expected at (eval 5) line 2, near "say "Hello Safe!""
(Do you need to predeclare say?)
Safe compartment error! syntax error at (eval 5) line 2, near "say "Hello Safe!""
% perl5.10.1 safe.pl
Running safe.pl under v5.10.1 with Safe 2.35
String found where operator expected at (eval 5) line 2, near "say "Hello Safe!""
(Do you need to predeclare say?)
Safe compartment error! syntax error at (eval 5) line 2, near "say "Hello Safe!""
状态不起作用,但中断方式不同
状态不同。
use v5.10;
use Safe;
say "Running $0 under $^V with Safe ", Safe->VERSION;
my $compartment = Safe->new;
$compartment->permit( ':base_io', ':load' );
my $code =<<'CODE';
use v5.10;
print "Hello Safe!\n";
foo();
sub foo {
state $n = 0;
print "n is $n\n";
}
CODE
$compartment->reval( $code ) or do {
my $error = $@;
warn "Safe compartment error! $@";
};
v5.18 和 v5.16 认为状态是语法错误:
% perl5.18.0 safe.pl
Running safe.pl under v5.18.0 with Safe 2.35
Hello Safe!
n is 0
% perl5.16.3 safe.pl
Running safe.pl under v5.16.3 with Safe 2.35
Hello Safe!
n is 0
在这些版本之前,我认为它被state
视为一种间接方法:
% perl5.14.4 safe.pl
Running safe.pl under v5.14.4 with Safe 2.35
Hello Safe!
Safe compartment error! Can't call method "state" on an undefined value at (eval 5) line 5.
给定
given
有同样的问题:
use v5.10;
use Safe;
say "Running $0 under $^V with Safe ", Safe->VERSION;
my $compartment = Safe->new;
$compartment->permit( ':base_io', ':load' );
my $code =<<'CODE';
use v5.10;
print "Hello Safe!\n";
my $foo = 'Buster Bean';
given( $foo ) {
when( /Buster/ ) { print "Buster\n" }
}
CODE
$compartment->reval( $code ) or do {
my $error = $@;
warn "Safe compartment error! $@";
};
它在 v5.16 和 v5.18 中运行良好:
% perl5.18.0 safe.pl
Running safe.pl under v5.18.0 with Safe 2.35
given is experimental at (eval 5) line 4.
when is experimental at (eval 5) line 5.
Hello Safe!
Buster
但在早期版本中中断:
% perl5.14.4 safe.pl
Running safe.pl under v5.14.4 with Safe 2.35
Safe compartment error! syntax error at (eval 5) line 4, near ") {"