如何在Perl中使用函数样式进行编码?
发布时间:2020-12-15 23:31:36 所属栏目:大数据 来源:网络整理
导读:你怎么样: 有一个子返回一个子 要么 执行文本作为代码 在Perl? 另外,我如何拥有匿名函数存储状态? 解决方法 sub返回一个sub作为coderef: # example 1: return a sub that is defined inline.sub foo{ return sub { my $this = shift; my @other_params =
你怎么样:
>有一个子返回一个子 要么 在Perl? 另外,我如何拥有匿名函数存储状态? 解决方法
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; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |