将项目从perl 5.8.8更新到perl 5.18.2时遇到问题。
我已将问题简化为以下示例:
use threads;
my $key = "abcdef";
print "test1 key = $key.\n";
my $thr = threads->create(sub {
eval "print \"test2 key = \$key.\n\";";
});
$thr->join();
在perl 5.8.8中,这给出了正确的输出:
test1 key = abcdef.
test2 key = abcdef.
但是在perl 5.18.2中,我有:
test1 key = abcdef.
test2 key = .
我尝试了其他perl版本,但问题似乎在5.14.0版本中出现。我正在寻找纠正此问题的最佳方法,以及有关此perl beaviour修改的说明。
我找到了一些替代方案,但对我来说似乎都不对:
对于我来说,在eval命令中使用$ key代替\ $ key并不是解决方案,因为在实际程序中,我将处理更复杂的结构。
该问题与线程无关。参见类似的PerlMonks线程。要创建一个闭包,编译器需要知道将使用一个变量。您可以在要关闭的子项中提及变量:
my $thr = threads->create(sub {
$key; # Create a closure.
eval "print \"test2 key = \$key.\n\";";
});
要查看类似的非线程情况,只需创建一个作用域:
my $sub = do {
my $key = "abcdef";
print "test1 key = $key.\n";
sub {
$key; # <-- Comment this line to get no value.
eval "print \"test2 key = \$key.\n\";";
}
};
$sub->();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句