yoda54 has asked for the wisdom of the Perl Monks concerning the following question:

Greetings Monks,

Is it possible to do something like this? I'd like to use eval to generate a bunch of function pointers during runtime and I'd like to be able to pass in and retrieve parameters.

Thanks!

my $a = 'return $_[0] + $_[1];'; print eval $a(3, 5); or perhaps: my $a = 'return $_[0] + $_[1];'; print eval $a->(3, 5);

Replies are listed 'Best First'.
Re: eval code generation - parameters & return values
by muba (Priest) on Jun 17, 2012 at 04:46 UTC

    Would anonymous subroutines do what you need?

    my $a = sub { return $_[0] + $_[1]; }; print $a->(3, 5);

    Edit: if you really need to do it runtime -- that is, dynamically, how about this:

    my $code = 'return $_[0] + $_[1];' my $a = eval "sub { $code }"; print $a->(3, 5);

    One thing to consider is that $a is a special variable, used by sort, so you might not want to use that name, but the technique still holds I think.

      Thanks for the help!!
Re: eval code generation - parameters & return values
by CountZero (Bishop) on Jun 17, 2012 at 08:05 UTC
    Why didn't you try it yourself?

    You would have seen that the first example throws a syntax error and the second example does not run under 'use strict' or when not running under the usual strictures, it gives an "Undefined subroutine &main::return $_[0] + $_1;" error.

    Those last errors are tips in the right direction: they tell you that your syntax expects a subroutine reference in your variable. It also tells you that it is probably not a good idea to do it as it violates the principles of 'use strict'.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics
Re: eval code generation - parameters & return values
by Khen1950fx (Canon) on Jun 17, 2012 at 16:08 UTC
    I have to agree with CountZero. There be dragons there. I stopped using string evals because they always find a way to come back and bite me. There are times when using a string eval is necessary, but it's not here. Here's a script that I did using Eval::WithLexicals.
    #!/usr/bin/perl use autodie; use strictures 1; use Eval::WithLexicals; use Data::Dumper::Concise; my($x) = Eval::WithLexicals->new(); my $y = 3; my $z = 5; use strict 'refs'; eval { $x = $y + $z; return; }; print Dumper($x);