解决方法
sub返回一个sub作为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 eval中的文档:
eval q{print "hello world!\n"};
请注意,如果您正在评估从用户输入中提取的任何内容,这是非常危险的,并且通常是一种不好的做法,因为您通常可以在coderef中定义代码,如上面的示例中所示.
您可以使用state variable(new in perl5.10)或使用高于子本身的变量作为closure存储状态:
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; } }