Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I code in a functional style in Perl?

How do you either:

  1. have a sub return a sub

    or

  2. execute text as code

in Perl?

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

like image 906
Ritwik Bose Avatar asked Nov 27 '22 05:11

Ritwik Bose


1 Answers

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

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

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

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.

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;
    }
}
like image 112
Ether Avatar answered Dec 15 '22 22:12

Ether