How to interpret a string as perl code and execute it without eval?

Tag: perl Author: superbbgo Date: 2012-07-21

I understand that "string-eval" can be used for it. But I am looking for some alternative to achieve it without eval. Reason being "string-eval" fail the perl critic and as per client policy I can not use it.

So, please tell me some alternative to do that without eval.

Here is what I am trying to do:

I am passing a dynamic generated code ref to a function. This function evaluates this code ref and assign the result to a variable.

If you can't eval as per client policy, trying to find something that does the same thing using some other construct doesn't sound like a good idea at all. Find another way of doing what it is you need to do.
Your best bet is to ask another question, explaining what you want to do and people will tell you how to do it without eval.
Have you tried writing the eval string to a seperate file and executing it (via do)?
Evaluating dynamic code is almost never a good idea.
Show us what is in this code ref string that you want to compile

Best Answer

Coderefs do not need eval to run. Simply dereference a coderef to invoke it. This is explained in perldoc perlref.

my $code = sub {
    my ($name) = @_;
    say "Hi, $name!";
};
$code->('rpg');

Other Answer1

Perl critic objects to string-eval because "interpreting a string as perl code and executing it" is generally a poor solution to any problem.

You can't work around it by just finding another function to do the same thing (well, you could, but that would be entirely missing the point).

comments:

Thank you very much. Your answer is great, appreciate your prompt response. But quick way to resolve it can be done by daxim's reply.

Other Answer2

This works for me.

#!/usr/bin/perl
use strict;
use warnings;

sub exec_code {
my ($c)[email protected]_;
return &{$c};
}

my $coderef = sub {
    print "Hello, from sub";
};

exec_code($coderef);