如何在Perl中以功能样式进行编码? [英] How can I code in a functional style in Perl?

查看:58
本文介绍了如何在Perl中以功能样式进行编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您怎么办?

  1. 具有sub返回sub

将文本作为代码执行

在Perl中?

还有,我如何具有匿名函数存储状态?

Also, how do I have an anonymous function store state?

推荐答案

一个sub返回一个sub作为 coderef :

A sub returns a sub as a 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中的文档评估:

Arbitrary text can be executed with the eval function: see the documentation at perldoc -f eval:

eval q{print "hello world!\n"};

请注意,如果您要评估从用户输入中提取的任何内容,这是非常危险的,并且无论如何通常都是不好的做法,因为您通常可以像上面前面的示例一样在coderef中定义代码.

Note that this is very dangerous if you are evaluating anything extracted from user input, and is generally a poor practice anyway as you can generally define your code in a coderef as in the earlier examples above.

您可以使用状态变量(新加入perl5.10)或变量的范围高于子项本身,例如

You can store state with a state variable (new in perl5.10), or with a variable scoped higher than the sub itself, as a 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;
    }
}

这篇关于如何在Perl中以功能样式进行编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆