如何在Perl中使用函数样式进行编码?

前端之家收集整理的这篇文章主要介绍了如何在Perl中使用函数样式进行编码?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
你怎么样:

>有一个子返回一个子

要么
>执行文本作为代码

在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;
    }
}

猜你在找的Perl相关文章