你如何:
-
have a sub
返回一个sub
or
将文本作为代码执行
in Perl?
另外,如何拥有匿名函数存储状态?
子返回子作为coderef:
# example 1: return a sub that is defined inline.
sub foo
{
return sub {
my $this = shift;
my @other_params = @_;
do_stuff();
return $some_value;
};
}
# example 2: return a sub that is defined elsewhere.
sub bar
{
return \&foo;
}
可以使用以下命令执行任意文本eval
功能:参见文档perldoc -f 评估 http://perldoc.perl.org/functions/eval.html:
eval q{print "hello world!\n"};
请注意,这是非常危险如果您正在评估从用户输入中提取的任何内容,那么通常这是一种不好的做法,因为您通常可以像上面的前面的示例一样在 coderef 中定义代码。
您可以使用以下方式存储状态状态变量 http://perldoc.perl.org/perlsub.html#Persistent-Private-Variables(perl5.10 中的新功能),或者使用作用域高于 sub 本身的变量,作为closure http://perldoc.perl.org/perlfaq7.html#What%27s-a-closure%3F:
use feature 'state';
sub baz
{
state $x;
return ++$x;
}
# create a new scope so that $y is not visible to other functions in this package
{
my $y;
sub quux
{
return ++$y;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)